3

Is there an easy way to recursively ZIP a directory that may or may not contain any number of files and any number of levels of subdirectories?

2
  • 1
    I checked Apache Commons Compress, and it's not there. Odd; "make a zip file outta this directory" seems like pretty common functionality.
    – Dean J
    Mar 8, 2010 at 18:54
  • FYI: You can do it in DotNetZip with ZipFile.AddDirectory();
    – Cheeso
    Mar 8, 2010 at 22:36

3 Answers 3

12
public final class ZipFileUtil {
    public static void zipDirectory(File dir, File zipFile) throws IOException {
        FileOutputStream fout = new FileOutputStream(zipFile);
        ZipOutputStream zout = new ZipOutputStream(fout);
        zipSubDirectory("", dir, zout);
        zout.close();
    }

    private static void zipSubDirectory(String basePath, File dir, ZipOutputStream zout) throws IOException {
        byte[] buffer = new byte[4096];
        File[] files = dir.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                String path = basePath + file.getName() + "/";
                zout.putNextEntry(new ZipEntry(path));
                zipSubDirectory(path, file, zout);
                zout.closeEntry();
            } else {
                FileInputStream fin = new FileInputStream(file);
                zout.putNextEntry(new ZipEntry(basePath + file.getName()));
                int length;
                while ((length = fin.read(buffer)) > 0) {
                    zout.write(buffer, 0, length);
                }
                zout.closeEntry();
                fin.close();
            }
        }
    }
}
1
  • Works well for me, but, for some mysterious reason, also adds files like 'java.io.FileInputStream@1c636e41' to the archive. Any idea on what I'm doing wrong? Oct 2, 2017 at 11:29
1

You can use the Java API Specification and How do you recursively traverse through file folders?.

-2

I use the ZipFileSystem implementation in ruby with great success, though I've never used it in java. You might want to check this out:

1
  • Link in answer is dead (404 Not Found).
    – Pang
    Jan 13, 2016 at 3:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.