在可执行 jar 中加载 xml 文件给出错误文件无法找到,从 eclipse 运行没问题
我有一个小型 Maven 应用程序,它从类路径加载 xml 文件并执行一些操作。它在 Eclipse 中运行良好,但是当我运行 maven:assemble 并获取带有依赖项的可执行 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);
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 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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试将其更改
为
:我不知道这是否有任何区别,但我会使用当前类的类加载器。
Try changing this:
to this:
I don't know if it makes any difference, but I would use the class loader for the current class.