'Java: ZipFile using Path

I have a Path to zip file on virtual filesystem (jimfs) and I need to open this zip file using ZipFile.

But there is no constructor in ZipFile to get Path as argument, only File.

However, I can't create from my Path a File (path.toFile()) because I get UnsupportedOperationException. How can I open my zip file with ZipFile? Or maybe there are other ways of working with zip files which are not on default filesystem?



Solution 1:[1]

The ZipFile class is limited to files in the file-system.

An alternative would be to use ZipInputStream instead. Create an InputStream from your Path using

Path path = ...
InputStream in = Files.newInputStream(path, openOptions)

and the use the InputStream to create an ZipInputStream. This way should work as expected:

ZipInputStream zin = new ZipInputStream(in)

So the recommended way to use it is:

try (ZipInputStream zin = new ZipInputStream(Files.newInputStream(path))) {
    // do something with the ZipInputStream
}

Note that decompressing certain ZIP files using ZipInputStream will fail because of their ZIP structure. This is a technical limitation of the ZIP format and can't be solved. In such cases you have to create a temporary file in file-system or memory and use a different ZIP class like ZipFile.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1