Lets say I have a file t.txt, a directory t and another file t/t2.txt. If I use the linux zip utility "zip -r t.zip t.txt t", I get a zip file with the following entries in them (unzip -l t.zip):
Archive: t.zip Length Date Time Name -------- ---- ---- ---- 9 04-11-09 09:11 t.txt 0 04-11-09 09:12 t/ 15 04-11-09 09:12 t/t2.txt -------- ------- 24 3 files
If I try to replicate that behavior with java.util.zip.ZipOutputStream and create a zip entry for the directory, java throws an exception. It can handle only files. I can create a t/t2.txt entry in the zip file and add use the t2.txt file contents to it but I can't create the directory. Why is that?
A Zip file is a data container containing one or more compressed files or directories. Compressed (zipped) files take up less disk space and can be transferred from one to another machine more quickly than uncompressed files.
Zipping a directory is little tricky, first we need to get the files list as absolute path. Then process each one of them separately. We need to add a ZipEntry for each file and use FileInputStream to read the content of the source file to the ZipEntry corresponding to that file.
write(byte[] buf, int off, int len) method writes an array of bytes to the current ZIP entry data. This method will block until all the bytes are written.
Just go through the source of java.util.zip.ZipEntry. It treats a ZipEntry as directory if its name ends with "/" characters. Just suffix the directory name with "/".
Check this example for zipping just the empty directories, http://bethecoder.com/applications/tutorials/showTutorials.action?tutorialId=Java_ZipUtilities_ZipEmptyDirectory
Good luck.
ZipOutputStream
can handle empty directories by adding a forward-slash /
after the folder name. Try (from)
public class Test { public static void main(String[] args) { try { FileOutputStream f = new FileOutputStream("test.zip"); ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(f)); zip.putNextEntry(new ZipEntry("xml/")); zip.putNextEntry(new ZipEntry("xml/xml")); zip.close(); } catch(Exception e) { System.out.println(e.getMessage()); } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With