Skip to content

Using recursive zipping of directory and subdirectory

I have decided to start posting things on Java. And the first one is how to use 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\\");
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);



To add directories:

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

To add files:

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

Posted in Java. Tagged with , , .