How to Zip a Folder in Java

Java has a good library of classes for handling zip files. These classes are available in the java.util.zip package. The following example program in Java shows how you can use java.util.zip classes to create a zip of an entire folder. We use the Files.walkFileTree to recursively navigate through the directory tree and then add each file into the newly created zip file. Please note that this example works only in Java 1.7 and above.

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

// Source code to create a zip file from a given folder
// This example program recursively adds all files in the folder
// Works only with Java 7 and above
public class ZipFolder {
    public static void main(String[] args) throws Exception {
        ZipFolder zf = new ZipFolder();
        
        // Use the following paths for windows
        //String folderToZip = "c:\\demo\\test";
        //String zipName = "c:\\demo\\test.zip";
        
        // Linux/mac paths
        String folderToZip = "/Users/jj/test";
        String zipName = "/Users/jj/test.zip";
        zf.zipFolder(Paths.get(folderToZip), Paths.get(zipName));
    }

    // Uses java.util.zip to create zip file
    private void zipFolder(Path sourceFolderPath, Path zipPath) throws Exception {
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipPath.toFile()));
        Files.walkFileTree(sourceFolderPath, new SimpleFileVisitor<Path>() {
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                zos.putNextEntry(new ZipEntry(sourceFolderPath.relativize(file).toString()));
                Files.copy(file, zos);
                zos.closeEntry();
                return FileVisitResult.CONTINUE;
            }
        });
        zos.close();
    }
}

In linux/mac, you can test the newly created zip file using the following command,

unzip -t test.zip

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish the solution! Please email us.

Leave a Reply