How to Zip a Folder in Java

Java has a good library of classes for handling zip files. These classes are available in the package. The following example program in Java shows how you can use 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.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;

// 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\\";
        // Linux/mac paths
        String folderToZip = "/Users/jj/test";
        String zipName = "/Users/jj/";
        zf.zipFolder(Paths.get(folderToZip), Paths.get(zipName));

    // Uses 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);
                return FileVisitResult.CONTINUE;

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

unzip -t