Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading File In JAR using Relative Path

I have some text configuration file that need to 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, though I did have to do that hack to deal with the space in the path name. The config file is in the same package as the method above. However, when I export the application as a jar I am having problems with it. The jar exists on a shared, mapped network drive Z:. When I run the application from command line I get this error:

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

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

Thanks, Jonah

like image 660
Jonah Avatar asked Feb 20 '11 00:02

Jonah


People also ask

How do you read a relative path?

Relative paths make use of two special symbols, a dot (.) and a double-dot (..), which translate into the current directory and the parent directory. Double dots are used for moving up in the hierarchy. A single dot represents the current directory itself.

How do I run a path from a JAR file?

In Java, we can use the following code snippets to get the path of a running JAR file. // static String jarPath = ClassName. class . getProtectionDomain() .

How do I view files in a JAR file?

JAR files are packaged in the ZIP file format. The unzip command is a commonly used utility for working with ZIP files from the Linux command-line. Thanks to the unzip command, we can view the content of a JAR file without the JDK.


1 Answers

When the file is inside a jar, you can't use the File class to represent it, since it is a jar: URI. Instead, the URL class itself already gives you with openStream() the possibility to read the contents.

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

To get a BufferedReader (which is easier to use, as it has a readLine() method), use the usual stream-wrapping:

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 (i.e. which you used in the editor).


Another point: Even if you only have file: URIs, you should not do the URL to File-conversion yourself, instead use new File(url.toURI()). This works for other problematic characters as well.

like image 156
Paŭlo Ebermann Avatar answered Sep 19 '22 12:09

Paŭlo Ebermann