Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a file from JAR using NIO?

Tags:

java

jar

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.

like image 312
TwoThe Avatar asked Oct 10 '13 19:10

TwoThe


People also ask

Can you view code from a JAR file?

Jar files are archive files that contains of a lot of different java classes (files). You can use winzip/winrar to open the jar files and you can see those java classes in jar files. Typically you can use a Java decompiler to decompile the class file and look into the source code.

How do I read a JAR file in Unix?

JAR files are packaged in the ZIP file format. The unzip command is a commonly used utility for working with ZIP files from the Linux command-line. Thanks to the unzip command, we can view the content of a JAR file without the JDK.


1 Answers

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)

like image 99
TwoThe Avatar answered Oct 09 '22 07:10

TwoThe