
import java.io.OutputStream;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.net.*;

public class ZipFSNewOutputStream {

	public static void main(final String[] args) throws Exception {
		System.out.println("Running tests using " + System.getProperty("java.version"));
		final Path jarPath = Paths.get("zipfs-outstream-test.jar");
        // cleanup existing jar
        if (Files.exists(jarPath)) {
            Files.delete(jarPath);
            System.out.println("Deleted " + jarPath + " in preparation for tests");
        }
        final String pathWithinJar = "foo.txt";
        final URI zipFsUri = new URI("jar:" + jarPath.toUri().getScheme(), jarPath.toUri().getPath(), null);
        try (final FileSystem zipFs = FileSystems.newFileSystem(zipFsUri, Collections.singletonMap("create", "true"))) {
            // create some file within the jar
            addContent(zipFs, pathWithinJar);
            System.out.println("Added " + pathWithinJar + " into " + jarPath);
        }
        System.out.println("Created file using zipfs at " + jarPath);
        // now open it again and then try to write content within it, at the same path again
        try (final FileSystem zipFs = FileSystems.newFileSystem(zipFsUri, Collections.singletonMap("create", "true"))) {
            System.out.println("Re-opening and attempting to add " + pathWithinJar + " into " + jarPath);
            // create some file within the jar
            addContent(zipFs, pathWithinJar);
        }
	}

	private static void addContent(final FileSystem zipFs, final String path) throws Exception {
		final Path filePath = zipFs.getPath(path);
        try (final OutputStream os = Files.newOutputStream(filePath)) {
            final byte[] someData = new byte[]{'b', 'c', 'd'};
            os.write(someData);
        }
	}
}