简体   繁体   中英

How to read a file from JAR using NIO?

Reading a file from the executable JAR file itself using ClassLoader.getResourceAsStream(...) is a known concept to me, but how would I do the same using Java NIO?

The target is to have a function as follows:

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);
}

While this works fine in the IDE, I get a

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

when I try this with the real JAR, even though the target file is in the correct place.

It turns out that my code above is actually correct, the issue is within Java itself.

According to this Bug ID , Java is not properly using the ZipFileSystemProvider as it should. Supposed to be fixed in Java 8. (My actual problem is described in this duplicate report )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM