Getting FileSystemNotFoundException from ZipFileSystemProvider when creating a path to a resource

You need to create the file system before you can access the path within the zip like

final URI uri = getClass().getResource("/my-folder").toURI();
Map<String, String> env = new HashMap<>(); 
env.put("create", "true");
FileSystem zipfs = FileSystems.newFileSystem(uri, env);
Path myFolderPath = Paths.get(uri);

This is not done automatically.

See http://docs.oracle.com/javase/7/docs/technotes/guides/io/fsp/zipfilesystemprovider.html


If you intend to read the resource file, you can directly use getClass.getResourceAsStream. This will set up the file system implictly. The function returns null if your resource could not be found, otherwise you directly have an input stream to parse your resource.


Expanding on @Uwe Allner 's excellent answer, a failsafe method to use is

private FileSystem initFileSystem(URI uri) throws IOException
{
    try
    {
        return FileSystems.getFileSystem(uri);
    }
    catch( FileSystemNotFoundException e )
    {
        Map<String, String> env = new HashMap<>();
        env.put("create", "true");
        return FileSystems.newFileSystem(uri, env);
    }
}

Calling this with the URI you are about to load will ensure the filesystem is in working condition. I always call FileSystem.close() after using it:

FileSystem zipfs = initFileSystem(fileURI);
filePath = Paths.get(fileURI);
// Do whatever you need and then close the filesystem
zipfs.close();

Tags:

Java

Maven