【发布时间】:2016-08-26 13:40:25
【问题描述】:
我的应用程序加载了一个位于 PROJECTNAME/resource 文件夹中的 txt 文件。
这是我加载文件的方式:
URL url = getClass().getClassLoader().getResource("batTemplate.txt");
java.nio.file.Path resPath;
String bat = "";
try {
resPath = java.nio.file.Paths.get(url.toURI());
bat = new String(java.nio.file.Files.readAllBytes(resPath), "UTF8");
} catch (URISyntaxException | IOException e1) {
e1.printStackTrace();
}
注意:这在我从 Eclipse 运行时有效,而在我导出到 Jar 文件时不起作用(将所需的库提取到生成的 JAR 中)。 我知道该文件正在被提取,因为它在 JAR 文件中。图像也可以工作。
错误信息:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException:
Illegal character in path at index 38: file:/C:/DataTransformation/Reports Program/ReportsSetup.jar
at com.sun.nio.zipfs.ZipFileSystemProvider.uriToPath(ZipFileSystemProvider.java:87)
at com.sun.nio.zipfs.ZipFileSystemProvider.getFileSystem(ZipFileSystemProvider.java:166)
at com.sun.nio.zipfs.ZipFileSystemProvider.getPath(ZipFileSystemProvider.java:157)
at java.nio.file.Paths.get(Unknown Source)
at ReportSetup$13.mouseReleased(ReportSetup.java:794)
我也在这里查看了类似的问题,但是它们指的是 JAR 文件之外的文件/URL。
【问题讨论】:
-
.jar 条目不是文件。您无法将资源转换为 Path。改为使用 getResourceAsStream 读取。
-
@VGR 谢谢,我改成了getResourceAsStream。它现在可以工作了:)
-
@VGR 请作为答案发布。我会接受的