Hi,
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.
views:
46answers:
5Add that file to the class path in your JAR manifest and read it as an input stream.
(new File(".")).getAbsolutePath();
Should give you the jar path. Print it out to double check, and then build your relative path onto it.
You could try this : Obtaining relative path outside of executable JAR
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.
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());
// ...