How to read external xml file from jar

瘦欲@ 提交于 2019-12-06 08:22:28

问题


i need to read an external XML file from my java application in jar executable file.
If I lunch it from console (java -jar package.jar) it works fine, but if I lunch it by double click (Java Platform SE binary) it don't work.
I have this problem with relative path. With absolute path it work in both way.


回答1:


You need to add the (JAR-relative) path to the XML tile to the Class-Path entry in the MANIFEST.MF file. This entry contains information about the JAR's runtime classpath. Assuming that you'd like to have the XML in the same folder as the JAR file itself, the following suffices:

Class-Path: .

(don't forget to put a blank line at end of MANIFEST.MF file)

Then you can obtain it as a classpath resource using Class#getResource() or ClassLoader#getResource(). The first suffices in your case.

URL xmlResource = getClass().getResource("/filename.xml");
File xmlFile = new File(xmlResource.getPath());
// ...



回答2:


Add that file to the class path in your JAR manifest and read it as an input stream.




回答3:


You could try this : Obtaining relative path outside of executable JAR




回答4:


(new File(".")).getAbsolutePath();

Should give you the jar path. Print it out to double check, and then build your relative path onto it.




回答5:


It's hard to give a precise answer without knowing what OS you are running.

The general answer would be to modify your launcher (the icon on the desktop) in order to specify the initial working directory to be the same as the one you use when you run the command from a shell.



来源:https://stackoverflow.com/questions/3668625/how-to-read-external-xml-file-from-jar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!