java 使用相对路径读取 JAR 中的文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5054435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading File In JAR using Relative Path
提问by Jonah
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:
当我在 eclipse 中本地运行它时,这有效,尽管我确实必须进行该 hack 来处理路径名中的空格。配置文件与上述方法在同一个包中。但是,当我将应用程序导出为 jar 时,我遇到了问题。jar 存在于共享的映射网络驱动器 Z: 上。当我从命令行运行应用程序时,出现此错误:
java.io.FileNotFoundException: file:\Z:\apps\jar\apps.jar!\vp\fsm\configs\wof.txt
java.io.FileNotFoundException: 文件:\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.
我怎样才能让它工作?我只想告诉java读取与当前类相同目录中的文件。
Thanks, Jonah
谢谢,约拿
回答by Pa?lo Ebermann
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.
当文件在 jar 中时,您不能使用File
该类来表示它,因为它是一个jar:
URI。相反,URL 类本身已经为您提供openStream()
了阅读内容的可能性。
Or you can shortcut this by using getResourceAsStream()
instead of getResource()
.
或者您可以使用getResourceAsStream()
代替getResource()
.
To get a BufferedReader (which is easier to use, as it has a readLine()
method), use the usual stream-wrapping:
要获得 BufferedReader(它更容易使用,因为它有一个readLine()
方法),请使用通常的流包装:
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).
使用文件实际使用的编码(即您在编辑器中使用的编码)代替“UTF-8”。
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.
另一点:即使你只有file:
URI,你也不应该自己做 URL 到文件转换,而是使用new File(url.toURI())
. 这也适用于其他有问题的角色。