【问题标题】:URL getResource not working when in JAR file在 JAR 文件中 URL getResource 不起作用
【发布时间】: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 请作为答案发布。我会接受的

标签: java eclipse jar


【解决方案1】:

.jar 条目不是文件;它是 .jar 档案的一部分。无法将资源转换为路径。您需要改用getResourceAsStream 来阅读它。

要阅读所有内容,您有几个选择。您可以使用扫描仪:

try (Scanner s = new Scanner(getClass().getClassLoader().getResourceAsStream("batTemplate.txt"), "UTF-8")) {
    bat = s.useDelimiter("\\Z").next();
    if (s.ioException() != null) {
        throw s.ioException();
    }
}

您可以将资源复制到临时文件中:

Path batFile = Files.createTempFile("template", ".bat");
try (InputStream stream = getClass().getClassLoader().getResourceAsStream("batTemplate.txt")) {
    Files.copy(stream, batFile);
}

您可以简单地从 InputStreamReader 中读取文本:

StringBuilder text = new StringBuilder();
try (Reader reader = new BufferedReader(
    new InputStreamReader(
        getClass().getClassLoader().getResourceAsStream("batTemplate.txt"),
        StandardCharsets.UTF_8))) {

    int c;
    while ((c = reader.read()) >= 0) {
        text.append(c);
    }
}

String bat = text.toString();

【讨论】:

    【解决方案2】:

    我认为你应该试试 getClass().getResourceAsStream("/batTemplate.txt")。

    同时检查this。可能会有所帮助。

    【讨论】:

      猜你喜欢
      • 2017-08-01
      • 1970-01-01
      • 2017-04-01
      • 1970-01-01
      • 2012-04-28
      • 2013-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多