从 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());
BufferedReader 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, and then 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.
推荐答案
而不是尝试将资源作为 File 只需询问 ClassLoader 返回一个 InputStream 而不是通过 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
资源是否在 file.txt
资源中,这种方法都会以相同的方式工作code>classes/ 目录或 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 不是分层的
发生是因为 jar 文件中资源的 URI 看起来像这样:file:/example.jar!/file.txt代码>.您无法像普通的旧 文件.
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:
这篇关于从 jar 中读取资源文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!