Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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::appsjarapps.jar!vpfsmconfigswof.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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
121 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...