2

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)));
user207421
  • 305,947
  • 44
  • 307
  • 483
user1987607
  • 2,057
  • 6
  • 26
  • 53
  • If `path` is `"/usr/tool"` as you say (Is it? You should test `System.out.println(path);` and add the results to your question.), why don't you just write something like `table1 = path + "/files/file.txt"`? – Alden Oct 29 '16 at 08:50
  • The CLASSPATH is not a file. It is a list of directories and .jar files where .class files can be located. Unclear what you're asking. – user207421 Oct 29 '16 at 10:22

1 Answers1

2

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");
janos
  • 120,954
  • 29
  • 226
  • 236