Java - How to compress file in zip format

Posted on November 14, 2016


Package java.util.zip provides classes for reading and writing zip and gzip file formats.

In this post, we will learn how to compress a file and directory in zip format. A ZipOutputStream class is used to write data in zip format to an output stream. A zip file contains multiple entries which are represented by the ZipEntry class.

Compress a file

Here is an example of compressing a file.

ZipFileExample.java

package com.boraji.tutorial.io;

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

/**
 * @author imssbora
 */
public class ZipFileExample {
  public static void main(String[] args) {
    // Output zip file
    File zipfile = new File("MyFile.zip");
    // Input file to be compressed
    File inFile = new File("file.txt");

    FileInputStream fileInputStream = null;
    FileOutputStream fileOutputStream = null;
    ZipOutputStream zipOutputStream = null;
    try {
      fileInputStream = new FileInputStream(inFile);
      fileOutputStream = new FileOutputStream(zipfile);
      zipOutputStream = new ZipOutputStream(fileOutputStream);

      // Create ZipEntry
      ZipEntry entry = new ZipEntry(inFile.getName());

      // Set position of stream to the start of entry data
      zipOutputStream.putNextEntry(entry);

      // Write data to zipOutputStream
      byte[] data = new byte[1024];
      int i;
      while ((i = fileInputStream.read(data)) != -1) {
        zipOutputStream.write(data, 0, i);
      }

      // Closes the current ZIP entry and positions the stream for writing
      // the next entry
      zipOutputStream.closeEntry();

    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        if (fileInputStream != null) {
          fileInputStream.close();
        }
        if (zipOutputStream != null) {
          zipOutputStream.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}

 

Compress all files and subdirectories in a directory

This example recursively traverses the all files in a directory and write to them to a zip file using ZipOutputStream.

ZipDirectoryExample.java

package com.boraji.tutorial.io;

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

/**
 * @author imssbora
 */
public class ZipDirectoryExample {
  public static void main(String[] args) {
    File zipFile = new File("MyZip.zip");
    File directory = new File("D:/Work/java");
    FileOutputStream fileOutputStream = null;
    ZipOutputStream zipOutputStream = null;
    try {
      fileOutputStream = new FileOutputStream(zipFile);
      zipOutputStream = new ZipOutputStream(fileOutputStream);

      // Create zip file
      createZipFile(zipOutputStream, directory, directory.getAbsolutePath());

    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        if (zipOutputStream != null) {
          zipOutputStream.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

  }

  /**
   * @param zipOutputStream
   * @param directory
   * @throws IOException
   */
  private static void createZipFile(ZipOutputStream zipOutputStream, File directory, String zipEntryPath) throws IOException {
    File[] files = directory.listFiles();
    for (File file : files) {
      if (file.isDirectory()) {
        createZipFile(zipOutputStream, file, zipEntryPath);
      } else {

        FileInputStream fileInputStream = new FileInputStream(file);

        // Create zipEntry
        String filePath = file.getAbsolutePath();
        ZipEntry entry = new ZipEntry(filePath.replace(zipEntryPath + File.separator, ""));

        // Set position of stream to the start of entry data
        zipOutputStream.putNextEntry(entry);

        // Write data to zip output stream
        byte data[] = new byte[1024];
        int i;
        while ((i = fileInputStream.read(data)) != -1) {
          zipOutputStream.write(data, 0, i);
        }

        // Closes the current ZIP entry
        zipOutputStream.closeEntry();

        // Close file stream
        fileInputStream.close();
      }
    }
  }
}