I have a small maven application, it loads an xml file from the classpath and does some manipulation. It runs fine from eclipse, but when I run maven:assembly, and get an executable jar with dependecies, the program executes up to the point where it needs to get the xml file, and then it gives:
java.io.FileNotFoundException: /home/ubuntu/Documents/workspaces/workspace-sts-2.7.2/test/target/file:
/home/ubuntu/Documents/workspaces/workspace-sts-2.7.2/test/target/test-0.0.1-SNAPSHOT-jar-with-dependencies.jar!/test.xml (No such file or directory)
the test.xml file is most certainly in the jar, and like 开发者_Python百科i said, it runs and finds the file just fine when running from eclipse. I believe the manifest file is setup correctly:
Manifest-Version: 1.0
Archiver-Version: Plexus Archiver
Created-By: Apache Maven
Built-By: ubuntu
Build-Jdk: 1.6.0_26
Main-Class: org.test.test1.App
Class-Path:.
here is the code that loads the xml file:
//load xml file from classpath
DocumentBuilder builder = factory.newDocumentBuilder();
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL classpathFileLocation =
classLoader.getResource("test.xml");
File file = new File(classpathFileLocation.getFile());
Document doc = builder.parse(file);
Try changing this:
URL classpathFileLocation = classLoader.getResource("test.xml");
File file = new File(classpathFileLocation.getFile());
to this:
InputStream is = classLoader.getResourceAsStream("test.xml");
Document doc = builder.parse(is); // Or look at the builder API to see what accepts InputStream
I don't know if it makes any difference, but I would use the class loader for the current class.
精彩评论