java - 从jar中读取资源文件

标签 java file jar resources embedded-resource

我想从我的 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/

相关文章:

java.lang.NoClassDefFoundError 尽管需要 jar

java - Bazel:带有 sqlite.db 的 Java 资源文件夹

java - 为什么 ArrayAdapter 只从数组的每个成员中检索一个对象,而不是整个对象?

python - 输入文件过大导致内存错误

c++从多个文件中读取多个数组

java - 向文件添加动态名称

java - Maven 应用程序在现实世界中是如何部署的?

java - 将 ssl 处理从 Tomcat 转移到 Apache?

java - 如何使用物理后退按钮返回浏览器的历史记录?

java - 在 TeamCity 中构建 IntelliJ 项目