我想从我的 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,我的文件所在的文件夹位于类文件夹中。
原文由 Koi 发布,翻译遵循 CC BY-SA 4.0 许可协议
与其尝试将资源作为 File 来处理,不如通过 getResourceAsStream 要求 ClassLoader 返回资源的 InputStream :
只要
file.txt
资源在类路径上可用,那么无论file.txt
资源是在classes/
目录中还是在里面一个jar
。出现
URI is not hierarchical
是因为 jar 文件中资源的 URI 看起来像这样:file:/example.jar!/file.txt
。您无法读取jar
(一个zip
文件)中的条目,就像它是一个普通的旧 文件 一样。答案很好地解释了这一点: