I’m developing a java application and I’m using gradle as my default build system. I love it so far I only have one problem: I read an config file like this in my java code:
URL url = Main.class.getResource("/configuration/Config.xml");
File file = new File(url.getFile());
When I run the program via eclipse, then it works without a problem. But when I generate the jar-file with the command “gradle build” then i get an exception. What am I doing wrong?
Oh sorry. Here’s my error message, when I try to execute the jar-file via console (with the command: “java -jar ResourceTest.jar”):
java.io.FileNotFoundException: D:\Tutorial\Spring\eclipse\workspace\ResourceTest\build\libs\file:\D:\Tutorial\Spring\eclipse\workspace\ResourceTest\build\libs\ResourceTest-1.0.jar!\configuration\Config.xml (Die Syntax für den Dateinamen, Verzeichnisnamen oder die Datenträgerbezeichnung ist falsch)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at sun.net.www.protocol.file.FileURLConnection.connect(Unknown Source)
at sun.net.www.protocol.file.FileURLConnection.getInputStream(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLVersionDetector.determineDocVersion(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
at javax.xml.parsers.DocumentBuilder.parse(Unknown Source)
at ch.example.bla.Main.main(Main.java:38)
I think I didn’t specify it before. But my gradle build runs without a problem. It generates the reports and the jar-file. I get the exception, when I run the jar file…
Looks like your code to turn the resource into a file doesn’t work when the resource is contained in a Jar (which it probably doesn’t when run from Eclipse). If all you need is to read the resource, use the ‘getResourceAsStream()’ method.