import java.io.OutputStream;
import java.net.URI;
import java.nio.file.*;
import java.util.Collections;
import java.util.zip.ZipOutputStream;

public class BugZipFileSystem {

    public static void main(String[] args) {
        try {
            System.out.println("Java version: "+System.getProperty("java.runtime.version"));
//1. Create a zip file
            Path zipFile = Files.createTempFile("buZipFilSystem", ".zip");
            try (OutputStream out = Files.newOutputStream(zipFile)) {
                new ZipOutputStream(out).close();
            }
            URI zipUri = new URI("jar:" + zipFile.toUri());

//2. Instantiate a ZipFileSystem
            FileSystem zipFs = FileSystems.newFileSystem(zipUri, Collections.EMPTY_MAP);

//3. Delete the source file
            Files.delete(zipFile);

//4. Close the ZipFileSystem
            try {
                zipFs.close();
            } catch (NoSuchFileException e) {
                System.out.println("zipFs.close() throw NoSuchFileException: not sure it was a good thing!");
                System.out.println("The internal Map jdk.nio.zipfs.ZipFileSystemProvider.filesystems is not correctly cleared");
            }

//5. Recreate the zip
            try (OutputStream out = Files.newOutputStream(zipFile)) {
                new ZipOutputStream(out).close();
            }

//6. It is now impossible to re-use the zipFs or instantiate a new one
            zipFs = FileSystems.getFileSystem(zipUri);
            if (!zipFs.isOpen()) System.out.println("zipFs is always internally referenced but closed and not usable");
            try {
                zipFs = FileSystems.newFileSystem(zipUri, Collections.EMPTY_MAP);
            } catch (Exception e) {
                System.out.println("A new ZipFs can not be instanciated because it is referenced in the internal map jdk.nio.zipfs.ZipFileSystemProvider.filesystems: " + e);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
} 