2

There's a runnable jar file and data.txt file next to it. data.txt may change dynamically. The program needs to read the content of this file. My first attempt at opening the file doesn't work:

new InputStreamReader(getClass().getResourceAsStream("/data.txt"), "UTF-8");

I came to the following solution, but it is complex and a little bit awkward:

new InputStreamReader(new FileInputStream(new File(getClass().getProtectionDomain().getCodeSource().getLocation().getPath()).getParent() + "/data.txt"), "UTF-8");

It is difficult to understand what is going on here.

I tried new File("./data.txt") and NPE was thrown.

How to open data.txt file that is in the same folder as .jar file, but in more readable way?

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
Dragon
  • 2,431
  • 11
  • 42
  • 68
  • I think the solution is in detail described here - http://stackoverflow.com/questions/8775303/read-properties-file-outside-jar-file – Jan Hruby Sep 03 '14 at 15:04
  • First off, don't write long-chain polymer statements, especially when you don't know what you're doing. They are impossible to debug. – Hot Licks Sep 03 '14 at 17:30
  • @HotLicks, in fact, I know what this specific statement does. But it needs time to understand for another person or even for me after some period of time. That's why I need better solution :) – Dragon Sep 03 '14 at 18:01
  • So, break it into steps, each step assigned to a temporary. Then you can easily debug it. And, horror of horrors, consider actually adding comments for each step. – Hot Licks Sep 03 '14 at 18:55

2 Answers2

2

There are two ways to locate the base path of a class file and you might find both being more complicated than necessary.

The first is what you have already in your question:

URL url = MyClass.class.getProtectionDomain().getCodeSource().getLocation();

the second is

URL url=MyClass.class.getResource("MyClass.class");
if(url.getProtocol().equals("jar"))
    url=((JarURLConnection)url.openConnection()).getJarFileURL();
else url=MyClass.class.getResource("/");// for file: directories

From the URL you can get a UTF-8 Reader with:

Reader r = Files.newBufferedReader(Paths.get(url.toURI()).resolveSibling("data.txt"));
Holger
  • 285,553
  • 42
  • 434
  • 765
0

Did you set the Class-Path of the Jar file? If you include a "." in the class path I think it will work as you initially envisioned.

In the Jar file's manifest:

Class-Path: .

In the code:

InputStream ins = getClass().getResourceAsStream("/data.txt");
... // do stuff with stream

I haven't tested this, but I've done stuff similar to it, I believe it will work.

markspace
  • 10,621
  • 3
  • 25
  • 39