簡體   English   中英

如何使用 NIO 從 JAR 讀取文件?

[英]How to read a file from JAR using NIO?

使用 ClassLoader.getResourceAsStream(...) 從可執行 JAR 文件本身讀取文件對我來說是一個已知的概念,但我如何使用 Java NIO 做同樣的事情?

目標是具有如下功能:

static String readFullyFromJar(String filename) {
    final Path path = Paths.get(Main.class.getResource(fileName).toURI());
    final byte[] bytes = Files.readAllBytes(path);
    return new String(bytes, CHARSET_ASCII);
}

雖然這在 IDE 中運行良好,但我得到了一個

java.nio.file.FileSystemNotFoundException
    at com.sun.nio.zipfs.ZipFileSystemProvider.getFileSystem(ZipFileSystemProvider.java:171))

當我用真正的 JAR 嘗試這個時,即使目標文件在正確的位置。

事實證明,我上面的代碼實際上是正確的,問題出在 Java 本身。

根據這個Bug ID ,Java 沒有正確使用 ZipFileSystemProvider。 應該在 Java 8 中修復。(我的實際問題在這個重復報告中描述)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM