Java: adding directories in a ZipOutputStream

Lately I had to write some Java code that consumes and generates zip files using the classes from the java.util.zip package. Although I wasn’t excited with the library, it is fairly simple and gets the job done. Here’s a very simple example:

FileOutputStream fos = new FileOutputStream("myfile.zip");
ZipOutputStream zos = new ZipOutputStream(fos);
zos.putNextEntry(new ZipEntry("myfile.txt"));
// write file's contents to zip stream
zos.closeEntry();
zos.close();

One small problem I faced was when I needed to add a directory entry in my output zip. The ZipEntry class has a isDirectory() method which is useful when reading entries from an ZipInputStream, however there is no setDirectory() method to explicitly specify that an entry refers to a directory.

The solution may be quite intuitive although it may not be very obvious: to specify a directory entry we simply have to add a '/' character at the end of the name:

FileOutputStream fos = new FileOutputStream("myfile.zip");
ZipOutputStream zos = new ZipOutputStream(fos);
zos.putNextEntry(new ZipEntry("mydir/"));
zos.putNextEntry(new ZipEntry("mydir/myfile.txt"));
// write file's contents to zip stream
zos.closeEntry();
zos.close();

I hope this helps! 🙂

This entry was posted in Uncategorized. Bookmark the permalink.

One Response to Java: adding directories in a ZipOutputStream

  1. Daniel says:

    Hi, Thank you for the information, it was helpful and quick

Leave a Reply

Your email address will not be published. Required fields are marked *