我有一个小的maven应用程序,它从类路径加载一个xml文件并进行一些操作。它从eclipse运行得很好,但是当我运行maven:assembly,并获得一个带有dependecies的可执行jar时,程序执行到需要获取xml文件的位置,然后它给出:
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)
test.xml文件肯定在jar中,就像我说的那样,它运行并在从eclipse运行时发现文件很好。我相信清单文件设置正确:
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:.
这是加载xml文件的代码:
//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);
答案 0 :(得分:1)
尝试更改此内容:
URL classpathFileLocation = classLoader.getResource("test.xml");
File file = new File(classpathFileLocation.getFile());
到此:
InputStream is = classLoader.getResourceAsStream("test.xml");
Document doc = builder.parse(is); // Or look at the builder API to see what accepts InputStream
我不知道它是否有任何区别,但我会将类加载器用于当前类。