How to Compress Files in ZIP format in Java

1. Overview

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

2. Compress Single File in ZIP Format Example

  1. Read file with “FileInputStream”
FileInputStream in = new FileInputStream("C:/Project_Work/samples/sample.txt");
  1. Create output zip file with "FileOutputStream"
FileOutputStream fos = new FileOutputStream("C:/Project_Work/samples/src_sample.zip")
  1. Add the file name to “ZipEntry” and output it to “ZipOutputStream“
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();
  }
 }
}

3. Compress Multiple Files in ZIP Format Example

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

4. Reference

Comments