user1987607 user1987607 - 11 months ago 47
Java Question

How to open a file in the same directory as the .jar file of the application?

I'm trying to load a .txt file into an arrayList in java using a combination of relative paths.
My jar file is in /usr/tool/dist/tool.jar
The file I want to load is in /usr/tool/files/file.txt

I think I was able to retrieve the path of my tool.jar, but how can I go from that path to the one where my file is?

I have the following code

// String path should give me '/usr/tool'
File f = new File(System.getProperty("java.class.path"));
File dir = f.getAbsoluteFile().getParentFile();
String path = dir.toString();
String table1 = this should represent /usr/tool/files/file.txt
BufferedReader buf_table1 = new BufferedReader(new FileReader(new File(table1)));

Answer Source

To find the path of your jar file being executed, java.class.path is not the right property. This property may contain more than one file, and you cannot know which is the right one. (See the docs.)

To find the path of the correct jar file, you can use this instead:

URL url = MainClass.class.getProtectionDomain().getCodeSource().getLocation().getPath();

Where MainClass the main class of your tool, or any other class in the same jar file.

Next, the parent File of a file is its directory. So the parent File of /usr/tool/dist/tool.jar is /usr/tool/dist/. So if you want to get to /usr/tool/files/file.txt, you need to get the parent of the parent, and then from there files/file.txt.

Putting it together:

File jarFile = new File(MainClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
File file = new File(jarFile.getParentFile().getParent(), "files/file.txt");