使用相对路径读取 JAR 中的文件 [英] Reading File In JAR using Relative Path

查看:23
本文介绍了使用相对路径读取 JAR 中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些文本配置文件需要我的程序读取.我当前的代码是:

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", " "));
}

当我在 eclipse 中本地运行它时,这有效,尽管我确实必须进行该 hack 来处理路径名中的空格.配置文件与上述方法在同一个包中.但是,当我将应用程序导出为 jar 时,我遇到了问题.jar 存在于共享的映射网络驱动器 Z: 上.当我从命令行运行应用程序时,出现此错误:

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

java.io.FileNotFoundException: file::appsjarapps.jar!vpfsmconfigswof.txt

我怎样才能让它工作?我只想告诉java读取当前类同目录下的文件

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

谢谢,约拿

推荐答案

当文件在 jar 中时,不能使用 File 类来表示它,因为它是一个 jar: URI.相反,URL 类本身已经为您提供了openStream() 读取内容的可能性.

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.

或者你可以通过使用 getResourceAsStream() 而不是 getResource() 来捷径.

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

要获得一个 BufferedReader(它更容易使用,因为它有一个 readLine() 方法),使用通常的流包装:

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"));

使用文件实际使用的编码(即您在编辑器中使用的编码)代替UTF-8".

Instead of "UTF-8" use the encoding actually used by the file (i.e. which you used in the editor).

另一点:即使你只有 file: URI,你也不应该自己做 URL 到 File-conversion,而是使用 new File(url.toURI())代码>.这也适用于其他有问题的角色.

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.

这篇关于使用相对路径读取 JAR 中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆