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

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

问题描述

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

  protected File getConfigFile(){
URL url = getClass()。getResource(wof 。文本);
返回新文件(url.getFile()。replaceAll(%20,));
}

当我在eclipse中本地运行它时,这是有效的,尽管我确实需要这样做黑客攻击路径名中的空间。配置文件与上述方法位于同一个包中。但是,当我将应用程序导出为jar时,我遇到了问题。 jar存在于共享的映射网络驱动器Z:上。当我从命令行运行应用程序时,我收到此错误:



java.io.FileNotFoundException:file:\ Z:\ apps\jar\apps。 jar!\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\我只想告诉java读取与当前类相同的目录中的文件。



谢谢,
Jonah

解决方案

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



或者你可以使用 getResourceAsStream()而不是 getResource()来快捷方式。



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

  InputStream configStream = getClass()。getResourceAsStream(wof.txt); 
BufferedReader configReader = new BufferedReader(new InputStreamReader(configStream,UTF-8));

而不是UTF-8使用文件实际使用的编码(即您在编辑)。






另一点:即使你只有文件: URI,你不应该自己做文件转换的URL,而是使用 new File(url.toURI())。这适用于其他有问题的角色。


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

解决方案

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.

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

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