从jar中读取资源文件 [英] Reading a resource file from within jar
问题描述
我想从我的jar中读取资源,如下所示:
I would like to read a resource from within my jar like so:
File file;
file = new File(getClass().getResource("/file.txt").toURI());
BufferredReader reader = new BufferedReader(new FileReader(file));
//Read the file
并且在运行时工作正常Eclipse,但是如果我将它导出到jar,那么运行它就会出现IllegalArgumentException:
and it works fine when running it in Eclipse, but if I export it to a jar the run it there is an IllegalArgumentException:
Exception in thread "Thread-2"
java.lang.IllegalArgumentException: URI is not hierarchical
我真的不知道为什么但是通过一些测试我发现如果我改变
and I really don't know why but with some testing I found if I change
file = new File(getClass().getResource("/file.txt").toURI());
到
file = new File(getClass().getResource("/folder/file.txt").toURI());
然后它正好相反(它适用于jar而不是eclipse)。
then it works the opposite (it works in jar but not eclipse).
我正在使用Eclipse,我的文件夹在一个类文件夹中。
I'm using Eclipse and the folder with my file is in a class folder.
推荐答案
而不是尝试将资源作为文件只要求 ClassLoader 返回通过 InputStream 获取资源=http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResourceAsStream%28java.lang.String%29 =noreferrer> getResourceAsStream :
Rather than trying to address the resource as a File just ask the ClassLoader to return an InputStream for the resource instead via getResourceAsStream:
InputStream in = getClass().getResourceAsStream("/file.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
只要 file.txt
资源在类路径上可用,无论 file.txt
资源是否在 classes / $ c $中,此方法都将以相同的方式工作c>目录或
jar
内。
As long as the file.txt
resource is available on the classpath then this approach will work the same way regardless of whether the file.txt
resource is in a classes/
directory or inside a jar
.
URI不是分层的$发生c $ c>因为jar文件中资源的URI看起来像这样:
file:/example.jar!/file.txt
。您无法读取 jar
(一个 zip
文件)中的条目,就像它是一个普通的文件。
The URI is not hierarchical
occurs because the URI for a resource within a jar file is going to look something like this: file:/example.jar!/file.txt
. You cannot read the entries within a jar
(a zip
file) like it was a plain old File.
以下答案解释了这一点:
This is explained well by the answers to:
- How do I read a resource file from a Java jar file?
- Java Jar file: use resource errors: URI is not hierarchical
这篇关于从jar中读取资源文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!