Skip to content


Using java.util.zip recursive zipping of directory and subdirectory

I have decided to start posting things on Java. And the first one is how to use java.util.zip to recursively zip a directory that contains:

  • File
  • Subdirectories
  • Empty subdirectories

The first two are straight forward, but the last one was a bit strange.

To add a file to zip (just an excerpt of code, may have missing try/except):

File f = new File("C:\\crx\\crx.zip");
ZipOutputStream zOut = new ZipOutputStream(new FileOutputStream(f));
String[] files = new String[] {"File1 (Full path)", "File2 (Full path)"};
String[] dirs = new String[] {"Full Path to directory 1","Full Path to directory 2"};
for(int i=0;i<files.length;i++) {
addFileToZip(files[i], zOut);
}

//now add all the directories
for(int i=0;i<dirs.length;i++) {
addDirectoryToZipRecursive(dirs[i], zOut);
}

zOut.flush();
zOut.close();

 

To add directories:

ZipEntry e = new ZipEntry(stripPath(path)+"/");
zip.putNextEntry(e);

To add files:

ZipEntry e = new ZipEntry(stripPath(f));
zip.putNextEntry(e);
FileInputStream in = new FileInputStream(f);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1)
zip.write(buffer, 0, bytesRead);
in.close();

Posted in Java. Tagged with , , .