How do I compress or zip a directory recursively?

In this example you are going to learn how to zip or compress a directory recursively. The zip file format allows us to compress multiple files. We use the to compress the file. Each entry in the zip file is represented by the class.

To compress a directory we must first get all the list of files in the specified directory and including all files in the subdirectory. In the example this task is handled by the getFileList() method. This method store the file list in the fileList variable to be use later during the compression process to create the ZipEntry.

Below is the code example showing you how to compress multiple files using zip.


import java.util.ArrayList;
import java.util.List;

public class ZipDirectoryExample {
    private final List<String> fileList = new ArrayList<>();

    public static void main(String[] args) {
        String dir = "D:/Data";
        String zipFile = "D:/";

        ZipDirectoryExample zip = new ZipDirectoryExample();
        zip.compressDirectory(dir, zipFile);

    private void compressDirectory(String dir, String zipFile) {
        File directory = new File(dir);

        try (FileOutputStream fos = new FileOutputStream(zipFile);
             ZipOutputStream zos = new ZipOutputStream(fos)) {

            for (String filePath : fileList) {
                System.out.println("Compressing: " + filePath);

                // Creates a zip entry.
                String name = filePath.substring(directory.getAbsolutePath().length() + 1);

                ZipEntry zipEntry = new ZipEntry(name);

                // Read file content and write to zip output stream.
                try (FileInputStream fis = new FileInputStream(filePath)) {
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = > 0) {
                        zos.write(buffer, 0, length);

                    // Close the zip entry.
                } catch (Exception e) {
        } catch (IOException e) {

     * Get files list from the directory recursive to the subdirectory.
    private void getFileList(File directory) {
        File[] files = directory.listFiles();
        if (files != null && files.length > 0) {
            for (File file : files) {
                if (file.isFile()) {
                } else {


The code snippet above will compress the D:\Data directory, and it will produce a zip file called When running the program you can see something like this in the console:

Compressing: D:\Data\Aa.txt
Compressing: D:\Data\AA1a1.txt
Compressing: D:\Data\Bb.txt
Compressing: D:\Data\Cc.txt
Compressing: D:\Data\CC1c1.txt
Compressing: D:\Data\Dd.txt

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.