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?