Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileSystem for zip file inside zip file

Tags:

java

java-nio

Can a java.nio.file.FileSystem be created for a zip file that's inside a zip file?

If so, what does the URI look like?

If not, I'm presuming I'll have to fall back to using ZipInputStream.

I'm trying to recurse into the method below. Current implementation creates a URI "jar:jar:...". I know that's wrong (and a potentially traumatic reminder of a movie character). What should it be?

private static void traverseZip(Path zipFile ) {
    // Example: URI uri = URI.create("jar:file:/codeSamples/zipfs/zipfstest.zip");
    
    String sURI = "jar:" + zipFile.toUri().toString();
    URI uri = URI.create(sURI);

    Map<String, String> env = new HashMap<>();

    try (FileSystem fs = FileSystems.newFileSystem(uri, env)) {

        Iterable<Path> rootDirs = fs.getRootDirectories();
        for (Path rootDir : rootDirs) {
            traverseDirectory(rootDir ); // Recurses back into this method for ZIP files
        }

    } catch (IOException e) {
        System.err.println(e);
    }
}
like image 249
Andy Thomas Avatar asked Jan 24 '26 09:01

Andy Thomas


1 Answers

You can use FileSystem.getPath to return a Path suitable for use with another FileSystems.newFileSystem call which opens the nested ZIP/archive.

For example this code opens a war file and reads the contents of the inner jar file:

Path war = Path.of("webapps.war");
String pathInWar = "WEB-INF/lib/some.jar";

try (FileSystem fs = FileSystems.newFileSystem(war)) {
    
    Path jar = fs.getPath(pathInWar);

    try (FileSystem inner = FileSystems.newFileSystem(jar)) {
        for (Path root : inner.getRootDirectories()) {
            try (Stream<Path> stream = Files.find(root, Integer.MAX_VALUE, (p,a) -> true)) {
                stream.forEach(System.out::println);
            }
        }
    }
}

Note also that you code can pass in zipFile without changing to URI:

try (FileSystem fs = FileSystems.newFileSystem(zipFile, env)) {
like image 139
DuncG Avatar answered Jan 26 '26 22:01

DuncG