我想从我的 jar 中读取资源,如下所示:
File file;
file = new File(getClass().getResource("/file.txt").toURI());
BufferedReader reader = new BufferedReader(new FileReader(file));
//Read the file
在 Eclipse 中运行它时工作正常,但是如果我将其导出到 jar,然后运行它,则会出现 IllegalArgumentException:
Exception in thread "Thread-2"
java.lang.IllegalArgumentException: URI is not hierarchical
我真的不知道为什么,但通过一些测试我发现如果我改变
file = new File(getClass().getResource("/file.txt").toURI());
至
file = new File(getClass().getResource("/folder/file.txt").toURI());
然后它的工作原理相反(它在 jar 中工作,但在 eclipse 中不起作用)。
我正在使用 Eclipse,并且包含我的文件的文件夹位于类文件夹中。
最佳答案
而不是尝试将资源寻址为 File只需询问 ClassLoader返回 InputStream通过 getResourceAsStream 获取资源:
try (InputStream in = getClass().getResourceAsStream("/file.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
// Use resource
}
只要 file.txt
资源在类路径上可用,那么无论 file.txt
资源是否位于 classes/
目录或 jar
内。
URI 不是分层的
,因为 jar 文件中资源的 URI 看起来像这样:file:/example.jar!/file.txt
.您无法像读取普通的旧 File 一样读取 jar
(zip
文件)中的条目。 .
以下问题的答案很好地解释了这一点:
关于java - 从jar中读取资源文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60613422/