Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

directories in a zip file when using java.util.zip.ZipOutputStream

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?

like image 205
Bala Avatar asked Apr 11 '09 16:04

Bala


People also ask

Can zip files contain directories?

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.

How do I zip a directory in Java?

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.

How do you use ZipOutputStream in Java?

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.


2 Answers

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.

like image 26
user769087 Avatar answered Oct 13 '22 22:10

user769087


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());         }     } } 
like image 66
John Ellinwood Avatar answered Oct 13 '22 23:10

John Ellinwood