Search code examples
javazipnio

Recreating a folder structure inside a Zip file with Java - Empty folders


I'm tried several ways to zip a directory structure in a zip file with Java. Don't matter if I use ZipOutputStream or the Java NIO zip FileSystem, I just can't add empty folders to the zip file.

I tried with unix zip, and it works as expected, so I discarded a possibly zip-format issue.

I could also do a little workaround, adding an empty file inside the folders, but I don't really want to do that.

Is there a way to add empty folders in zip files using java API's?


EDIT: Based on answers and comments, this is pretty much the solution I got.

Thanks!


Solution

  • Java NIO makes this as easy as working with a normal file system.

    public static void main(String[] args) throws Exception {
        Path zipfile = Paths.get("C:\\Users\\me.user\\Downloads\\myfile.zip");
    
        try (FileSystem zipfs = FileSystems.newFileSystem(zipfile, null);) {
            Path extFile = Paths.get("C:\\Users\\me.user\\Downloads\\countries.csv"); // from normal file system
            Path directory = zipfs.getPath("/some/directory"); // from zip file system
            Files.createDirectories(directory);
            Files.copy(extFile, directory.resolve("zippedFile.csv"));
        }
    }
    

    Given a myfile.zip file in the given directory, the newFileSystem call will detect the file type (.zip mostly gives it away in this case) and create a ZipFileSystem. Then you can just create paths (directories or files) in the zip file system and use the Java NIO Files api to create and copy files.

    The above will create the directory structure /some/directory at the root of the zip file and that directory will contain the zipped file.