使用相对路径读取 JAR 中的文件
我有一些文本配置文件需要由我的程序读取。我当前的代码是:
protected File getConfigFile() {
URL url = getClass().getResource("wof.txt");
return new File(url.getFile().replaceAll("%20", " "));
}
当我在 eclipse 中本地运行它时,这是有效的,尽管我确实必须执行该 hack 来处理路径名中的空格。配置文件与上述方法位于同一个包中。但是,当我将应用程序导出为 jar 时,我遇到了问题。该 jar 存在于共享的映射网络驱动器 Z: 上。当我从命令行运行应用程序时,出现此错误:
java.io.FileNotFoundException: file:\Z:\apps\jar\apps.jar!\vp\fsm\configs\wof.txt
如何才能使其正常工作?我只是想告诉java读取当前类所在目录中的文件。
谢谢, 约拿
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当文件位于 jar 内时,您不能使用
File
类来表示它,因为它是一个jar:
URI。相反,URL 类本身已经为您提供了使用openStream()
读取内容的可能性。或者,您可以使用
getResourceAsStream()
而不是getResource()
来简化此操作。要获取 BufferedReader(更容易使用,因为它有一个 readLine() 方法),请使用通常的流包装:
使用文件实际使用的编码而不是“UTF-8” (即您在编辑器中使用的)。
另一点:即使您只有
file:
URI,您也不应该自己进行 URL 到文件的转换,而应使用new File(url.toURI())
。这也适用于其他有问题的角色。When the file is inside a jar, you can't use the
File
class to represent it, since it is ajar:
URI. Instead, the URL class itself already gives you withopenStream()
the possibility to read the contents.Or you can shortcut this by using
getResourceAsStream()
instead ofgetResource()
.To get a BufferedReader (which is easier to use, as it has a
readLine()
method), use the usual stream-wrapping: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 usenew File(url.toURI())
. This works for other problematic characters as well.