How to Compress Files in ZIP Format in Java

In this article, we will show you how to compress single and multiple files to zip format. The example from this article uses a try-with-resources Statement to auto-close the resources and compiled and executed on JDK 8 and later.
 
Java comes with the “java.util.zip” library to perform data compression in ZIp format. 

1. Compress a Single File in ZIP Format Example

1. First, read the file with the “FileInputStream”
FileInputStream in = new FileInputStream("C:/Project_Work/samples/sample.txt");
2. Create an output zip file with "FileOutputStream"
FileOutputStream fos = new FileOutputStream("C:/Project_Work/samples/src_sample.zip")
3. Add the file name to “ZipEntry” and output it to “ZipOutputStream“

Here is the complete code to read a single file and convert it into a zip file:

Read a file “C:/Project_Work/samples/sample.txt” and compress it into a zip file – “C:/Project_Work/samples/src_sample.zip“.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * This Java program demonstrates how to compress single file in ZIP format.
 * @author javaguides.net
 */

public class CompressZipFile {
    public static void main(String[] args) {

        try (FileOutputStream fos = new FileOutputStream("C:/Project_Work/samples/src_sample.zip");
             ZipOutputStream zos = new ZipOutputStream(fos);
             FileInputStream in = new FileInputStream("C:/Project_Work/samples/sample.txt");) {
            ZipEntry ze= new ZipEntry("sample.txt");
            zos.putNextEntry(ze);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = in.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }

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

Compress Multiple Files in ZIP Format Example

Here is the complete code to compress multiple files to zip format:

Read all files from folder “C:\Project_Work\samples\src_sample” and compress it into a zip file – “C:\Project_Work\samples\dest_sample.zip“. It will recursively zip a directory as well.
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;

/**
 * This Java program demonstrates how to compress multiple files in ZIP format.
 *
 * @author javaguides.net
 *
 */
public class CompressMultipleFilesToZip {
    List<String> fileList;
    private static final String OUTPUT_ZIP_FILE = "C:\\Project_Work\\samples\\dest_sample.zip";
    private static final String SOURCE_FOLDER = "C:\\Project_Work\\samples\\src_sample";

    CompressMultipleFilesToZip() {
        fileList = new ArrayList<String>();
    }

    public static void main(String[] args) {
        CompressMultipleFilesToZip appZip = new CompressMultipleFilesToZip();
        appZip.generateFileList(new File(SOURCE_FOLDER));
        appZip.zipIt(OUTPUT_ZIP_FILE);
    }

    /**
     * Zip it
     *
     * @param zipFile
     *            output ZIP file location
     */
    public void zipIt(String zipFile) {

        byte[] buffer = new byte[1024];

        try (FileOutputStream fos = new FileOutputStream(zipFile); ZipOutputStream zos = new ZipOutputStream(fos);) {
            System.out.println("Output to Zip : " + zipFile);

            for (String file : this.fileList) {

                System.out.println("File Added : " + file);
                ZipEntry ze = new ZipEntry(file);
                zos.putNextEntry(ze);

                try (FileInputStream in = new FileInputStream(SOURCE_FOLDER + File.separator + file);) {
                    int len;
                    while ((len = in.read(buffer)) > 0) {
                        zos.write(buffer, 0, len);
                    }
                }
            }
            System.out.println("Done");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Traverse a directory and get all files, and add the file into fileList
     *
     * @param node
     *            file or directory
     */
    public void generateFileList(File node) {

        // add file only
        if (node.isFile()) {
            fileList.add(generateZipEntry(node.getAbsoluteFile().toString()));
        }

        if (node.isDirectory()) {
            String[] subNote = node.list();
            for (String filename : subNote) {
                generateFileList(new File(node, filename));
            }
        }

    }

    /**
     * Format the file path for zip
     *
     * @param file
     *            file path
     * @return Formatted file path
     */
    private String generateZipEntry(String file) {
        return file.substring(SOURCE_FOLDER.length() + 1, file.length());
    }
}
Output:
Output to Zip : C:\Project_Work\samples\dest_sample.zip
File Added : sample.txt
File Added : sample1.txt
File Added : sample2.txt
Done

References

Comments