Reading a file in a JAR using a relative path

I have a text configuration file that should be read by my program. My current code is:

protected File getConfigFile() { URL url = getClass().getResource("wof.txt"); return new File(url.getFile().replaceAll("%20", " ")); } 

This works when I run it locally in eclipse, although I had to do this hack to deal with the space in the path name. The configuration file is in the same package as the method above. However, when I export the application as a jar, I have problems with it. The box exists on a shared network drive Z :. When I launch the application from the command line, I get this error:

java.io.FileNotFoundException: file: \ Z: \ apps \ jar \ apps.jar! \ vp \ fsm \ configs \ wof.txt

How can I make this work? I just want to tell java to read the file in the same directory as the current class.

Thank you Jonah

+6
java jar
source share
1 answer

When a file is inside a flag, you cannot use the File class to represent it, since it is a jar: URI. Instead, the URL class itself already gives you the ability to openStream() to read the content.

Or you can shorten this by using getResourceAsStream() instead of getResource() .

To get a BufferedReader (which is easier to use since it has a readLine() method), use a regular stream wrapper:

 InputStream configStream = getClass().getResourceAsStream("wof.txt"); BufferedReader configReader = new BufferedReader(new InputStreamReader(configStream, "UTF-8")); 

Instead of “UTF-8,” use the encoding actually used by the file (ie you used it in the editor).


Another point: even if you only have a URI file: you should not use the URL to convert the files yourself, use new File(url.toURI()) instead. This also works for other problematic characters.

+14
source share

All Articles