How to read external xml file from jar

I need to read an external XML file from my java application in a jar executable.
If I dine it from the console (java -jar package.jar), it works fine, but if I dine it by double-clicking (Java Platform SE binary), it does not work.
I have this problem with a relative path. With an absolute path, it works in both directions.

+3
source share
5 answers

You need to add the path (JAR-relative) to the XML fragment to the entry Class-Pathin the file MANIFEST.MF. This entry contains path information for the runtime JAR class. Assuming you want the XML in the same folder as the JAR file itself, enough:

Class-Path: .

(don't forget to put an empty line at the end of the file MANIFEST.MF)

Then you can get it as a classpath resource with Class#getResource()or ClassLoader#getResource(). The first in your case is enough.

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

Add this file to the class path in the JAR manifest and read it as input.

+1
source

: JAR

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

. , , .

0

It is difficult to give an exact answer without knowing which OS you are working on.

The general answer is to change your launcher (the icon on the desktop) to specify the initial working directory as the one you use when you run the command from the shell.

0
source

Source: https://habr.com/ru/post/1763815/


All Articles