Zipping up directories from Java
The standard Java libraries come with a convenient package for reading and creating Zip files (java.util.zip). The class representing a Zip file entry has a method isDirectory() which can tell you whether the entry is a directory.
Unfortunately there is no counterpart, setDirectory(), that can be used when you are creating a zip file.
Usually this doesn’t matter, because when you zip up a file and provide it with a path, the unzipper will create all the directories required to store the file in that path. The only problem, then, is if you need to store empty directories which contain no associated files.
Several solutions are found on the web for this, usually involving storing a slightly different type of filename. The Java API documentation itself suggests that any path ending in a slash will be regarded as a directory. None of these solutions work.
The reason none of them work is that there is actually a bit in the Zip file specification which is used to represent directories (in fact, the relevant bit of the Zip file structure is entitled ‘external attributes’ and is supposed to represent the DOS equivalents – set bit 4 to represent a directory). You can find PHP, etc. code on the web setting this field to 16 to represent directories. The Java zip classes simply don’t set that bit.
Solutions:
- Use the zip library from Apache Commons, which does support these things.
- Use the Zip comments field (or special filenames) to store metadata about the entries you put in your zip. This only works if you also control the unzipping process.
