views:

46

answers:

5

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.

+1  A: 

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

duffymo
How can i add it ?
enfix
I read already it (db.parse(new File(filePath))), but i need to edit so i can't include it to the jar file.
enfix
No, not FilePath-that's brittle and error-prone. getResourceAsStream() is the correct way to read. Editing and writing are a different matter.
duffymo
A: 
(new File(".")).getAbsolutePath();

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

Peter DeWeese
This will return the current working directory, not the path of the jar file.
gawi
A: 

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

Damien
A: 

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.

gawi
A: 

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());
// ...
BalusC