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 java.util.zip.ZipOutputStream to compress the file. Each entry in the zip file is represented by the java.util.zip.ZipEntry class.

To compress a directory we must first get all the list of files in the specified directory and including all files in the sub directory. 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.

package org.kodejava.example.zip;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

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

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

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

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

        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,
                        filePath.length());
                ZipEntry zipEntry = new ZipEntry(name);
                zos.putNextEntry(zipEntry);

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

                //
                // Close the zip entry and the file input stream.
                //
                zos.closeEntry();
                fis.close();
            }

            //
            // Close zip output stream and file output stream. This will
            // complete the compression process.
            //
            zos.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

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

    }
}

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

Compressing: D:\DataAa.txt
Compressing: D:\DataAA1a1.txt
Compressing: D:\DataBb.txt
Compressing: D:\DataCc.txt
Compressing: D:\DataCC1c1.txt
Compressing: D:\DataDd.txt

How do I decompress a GZip file in Java?

In the previous example we have learn how to compress a file in GZIP format. To get the file back to its original version we will now learn how to decompress the gzip file. Just like the previous example, we are also going to use the FileInputStream and FileOutputStream class to read the compressed source file and to write out the decompressed file. While GZipOutputStream was used to to create the gzip file, the GZipInputStream is the class that handles the decompression.

Here is your code snippet:

package org.kodejava.example.zip;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;

public class GZipDecompressExample {
    public static void main(String[] args) {
        //
        // GZip input and output file.
        //
        String sourceFile = "core-sample/target/classes/output.gz";
        String targetFile = "core-sample/target/classes/input-1.txt";

        try {
            //
            // Create a file input stream to read the source file.
            //
            FileInputStream fis = new FileInputStream(sourceFile);

            //
            // Create a gzip input stream to decompress the source
            // file defined by the file input stream.
            //
            GZIPInputStream gzis = new GZIPInputStream(fis);

            //
            // Create a buffer and temporary variable used during the
            // file decompress process.
            //
            byte[] buffer = new byte[1024];
            int length;

            //
            // Create file output stream where the decompress result
            // will be stored.
            //
            FileOutputStream fos = new FileOutputStream(targetFile);

            //
            // Read from the compressed source file and write the
            // decompress file.
            //
            while ((length = gzis.read(buffer)) > 0) {
                fos.write(buffer, 0, length);
            }

            //
            // Close the resources.
            //
            fos.close();
            gzis.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How do I compress a file in GZip format?

In this code example we will learn how to compress a file using the gzip compression. By its nature, gzip can only compress a single file, you can not use it for compressing a directory and all the files in that directory.

Classes that you will be using to compress a file in gzip format includes the GZipOutputStream, FileInputStream and FileOutputStream classes. The steps for compressing a file described in the comments of the code snippet below.

package org.kodejava.example.zip;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

public class GZipCompressExample {
    public static void main(String[] args) {
        //
        // GZip input and output file.
        //
        String sourceFile = "core-sample/target/classes/input.txt";
        String targetFile = "core-sample/target/classes/output.gz";

        try {
            //
            // Create a file output stream the write the gzip result into
            // a specified file name.
            //
            FileOutputStream fos = new FileOutputStream(targetFile);

            //
            // Create a gzip output stream object with file output stream
            // as the argument.
            //
            GZIPOutputStream gzos = new GZIPOutputStream(fos);

            //
            // Define buffer and temporary variable for iterating the file
            // input stream.
            //
            byte[] buffer = new byte[1024];
            int length;

            //
            // Create a file input stream of the file that is going to be
            // compressed.
            //
            FileInputStream fis = new FileInputStream(sourceFile);

            //
            // Read all the content of the file input stream and write it
            // to the gzip output stream object.
            //
            while ((length = fis.read(buffer)) > 0) {
                gzos.write(buffer, 0, length);
            }

            //
            // Finish file compressing and close all streams.
            //
            fis.close();
            gzos.finish();
            gzos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How do I decompress Java objects?

In the previous example How do I compress Java objects? we have manage to compress Java objects and stored them in file. In this example we will read the file and reconstruct the compressed objects. For the User class you can see in the previous example mentioned above.

package org.kodejava.example.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.zip.GZIPInputStream;

public class UnzipObjectDemo {
    public static void main(String[] args) {
        User admin = null;
        User foo = null;

        try {
            FileInputStream fis = new FileInputStream(new File("user.dat"));
            GZIPInputStream gis = new GZIPInputStream(fis);
            ObjectInputStream ois = new ObjectInputStream(gis);

            admin = (User) ois.readObject();
            foo = (User) ois.readObject();

            ois.close();
            gis.close();
            fis.close();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        System.out.println("Admin = [" + admin + "]");
        System.out.println("Foo = [" + foo + "]");
    }
}

Running the code snippet above will give us the following output:

Admin = [User{id=1, username='admin', password='secret', firstName='System', lastName='Administrator'}]
Foo = [User{id=2, username='foo', password='secret', firstName='Foo', lastName='Bar'}]

How do I compress Java objects?

This example demonstrates how to compress a Java object. We compress the Java object using GZIPOutputStream, pass it to ObjectOutputStream to write the object into an external file. The object we are going to compress will be represented by the User object. We need to make the User object serializable so it must implements the java.io.Serializable interface. You can see the complete code snippet below.

package org.kodejava.example.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.zip.GZIPOutputStream;

public class ZipObjectDemo {
    public static void main(String[] args) {
        User admin = new User();
        admin.setId(1L);
        admin.setUsername("admin");
        admin.setPassword("secret");
        admin.setFirstName("System");
        admin.setLastName("Administrator");

        User foo = new User();
        foo.setId(2L);
        foo.setUsername("foo");
        foo.setPassword("secret");
        foo.setFirstName("Foo");
        foo.setLastName("Bar");

        System.out.println("Zipping....");
        System.out.println(admin);
        System.out.println(foo);
        try {
            FileOutputStream fos = new FileOutputStream(new File("user.dat"));
            GZIPOutputStream gos = new GZIPOutputStream(fos);
            ObjectOutputStream oos = new ObjectOutputStream(gos);

            oos.writeObject(admin);
            oos.writeObject(foo);

            oos.flush();
            oos.close();

            gos.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
package org.kodejava.example.util;

import java.io.Serializable;

public class User implements Serializable {
    private Long id;
    private String username;
    private String password;
    private String firstName;
    private String lastName;

    public User() {
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                '}';
    }
}

Running the code snippet will give us the following output:

Zipping....
User{id=1, username='admin', password='secret', firstName='System', lastName='Administrator'}
User{id=2, username='foo', password='secret', firstName='Foo', lastName='Bar'}

How do I read a zip file checksum value?

package org.kodejava.example.util;

import java.io.*;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.CheckedInputStream;
import java.util.zip.Adler32;

public class UnzipWithChecksum {
    public static void main(String[] args) {
        String zipname = "data-1.zip";

        try {
            FileInputStream fis = new FileInputStream(zipname);

            //
            // Creating input stream that also maintains the checksum of the
            // data which later can be used to validate data integrity.
            //
            CheckedInputStream checksum = new CheckedInputStream(fis, new Adler32());
            ZipInputStream zis = new ZipInputStream(new BufferedInputStream(checksum));
            ZipEntry entry;

            //
            // Read each entry from the ZipInputStream until no more entry found
            // indicated by a null return value of the getNextEntry() method.
            //
            while ((entry = zis.getNextEntry()) != null) {
                System.out.println("Unzipping: " + entry.getName());

                int size;
                byte[] buffer = new byte[2048];

                FileOutputStream fos = new FileOutputStream(entry.getName());
                BufferedOutputStream bos = new BufferedOutputStream(fos, buffer.length);

                while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
                    bos.write(buffer, 0, size);
                }
                bos.flush();
                bos.close();
            }

            zis.close();
            fis.close();

            //
            // Print out the checksum value
            //
            System.out.println("Checksum = " + checksum.getChecksum().getValue());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How do I create checksum for a zip file?

This example demonstrate how to use CheckedOutputStream for creating a checksum of a zip file. Checksum can be used to detect whether a data was corrupted during a transmission process to a remote machine.

package org.kodejava.example.util;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import java.util.zip.CheckedOutputStream;
import java.util.zip.Adler32;

public class ZipWithChecksum {
    public static void main(String[] args) {
        try {
            String target = "data-1.zip";

            FileOutputStream fos = new FileOutputStream(target);

            //
            // An output stream that also maintains a checksum of the data being
            // written. The checksum can then be used to verify the integrity of
            // the output data.
            //
            CheckedOutputStream checksum = new CheckedOutputStream(fos, new Adler32());
            ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(checksum));

            int size = 0;
            byte[] buffer = new byte[1024];

            //
            // Get all text files on the working folder.
            //
            File dir = new File(".");
            String[] files = dir.list(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    if (name.endsWith(".txt")) {
                        return true;
                    } else {
                        return false;
                    }
                }
            });

            for (int i = 0; i < files.length; i++) {
                System.out.println("Compressing: " + files[i]);

                FileInputStream fis = new FileInputStream(files[i]);
                BufferedInputStream bis = new BufferedInputStream(fis, buffer.length);

                // put a new ZipEntry in the ZipOutputStream
                ZipEntry zipEntry = new ZipEntry(files[i]);
                zos.putNextEntry(zipEntry);

                // read data to the end of the source file and write it to the zip
                // output stream.
                while ((size = fis.read(buffer, 0, buffer.length)) > 0) {
                    zos.write(buffer, 0, size);
                }

                zos.closeEntry();
                fis.close();
            }

            // Finish zip process
            zos.close();

            //
            // Print out checksum value
            //
            System.out.println("Checksum   : " + checksum.getChecksum().getValue());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How do I decompress a zip file using ZipFile?

In this example we use the java.util.zip.ZipFile class to decompress and extract a zip file.

package org.kodejava.example.util.zip;

import java.util.zip.ZipFile;
import java.util.zip.ZipEntry;
import java.util.Enumeration;
import java.io.*;

public class ZipFileUnzipDemo {
    public static void main(String[] args) {
        String zipname = "data.zip";

        try {
            ZipFile zipFile = new ZipFile(zipname);
            Enumeration enumeration = zipFile.entries();

            while (enumeration.hasMoreElements()) {
                ZipEntry zipEntry = (ZipEntry) enumeration.nextElement();
                System.out.println("Unzipping: " + zipEntry.getName());

                BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(zipEntry));

                int size;
                byte[] buffer = new byte[2048];

                FileOutputStream fos = new FileOutputStream(zipEntry.getName());
                BufferedOutputStream bos = new BufferedOutputStream(fos, buffer.length);

                while ((size = bis.read(buffer, 0, buffer.length)) != -1) {
                    bos.write(buffer, 0, size);
                }

                bos.flush();
                bos.close();
                fos.close();

                bis.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How do I decompress a zip file using ZipInputStream?

The code below shows how to decompress and extract files from a zip archive. In the example we use the java.util.zip.ZipInputStream class.

package org.kodejava.example.util.zip;

import java.io.*;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipEntry;

public class UnzipDemo {
    public static void main(String[] args) {
        String zipName = "data.zip";

        try {
            FileInputStream fis = new FileInputStream(zipName);
            ZipInputStream zis = new ZipInputStream(
                    new BufferedInputStream(fis));
            ZipEntry entry;

            //
            // Read each entry from the ZipInputStream until no
            // more entry found indicated by a null return value
            // of the getNextEntry() method.
            //
            while ((entry = zis.getNextEntry()) != null) {
                System.out.println("Unzipping: " + entry.getName());

                int size;
                byte[] buffer = new byte[2048];

                FileOutputStream fos =
                        new FileOutputStream(entry.getName());
                BufferedOutputStream bos =
                        new BufferedOutputStream(fos, buffer.length);

                while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
                    bos.write(buffer, 0, size);
                }
                bos.flush();
                bos.close();
            }

            zis.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How do I create a zip file?

package org.kodejava.example.util.zip;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZippingFileExample {
    public static void main(String[] args) {
        String source = "data.txt";
        String target = "data.zip";

        try {
            ZipOutputStream zos = new ZipOutputStream(
                    new FileOutputStream(target));

            // Create input stream to read file from resource folder.
            Class clazz = ZippingFileExample.class;
            InputStream is = clazz.getResourceAsStream("/" + source);

            // Put a new ZipEntry in the ZipOutputStream
            zos.putNextEntry(new ZipEntry(source));

            int size;
            byte[] buffer = new byte[1024];

            // Read data to the end of the source file and write it
            // to the zip output stream.
            while ((size = is.read(buffer, 0, buffer.length)) > 0) {
                zos.write(buffer, 0, size);
            }

            zos.closeEntry();
            is.close();

            // Finish zip process
            zos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}