views:

3184

answers:

2

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?

+2  A: 

It looks like ZipOutputStream can't handle empty directories, but you have a file in there so its not empty. 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());
     }
    }
}
John Ellinwood
A: 

You can at "/" at the end of folder name. Just use follow command zip.putNextEntry(new ZipEntry("xml/"));