How To Create A Zip File In Java

When dealing with zip files in Java, the process differs from handling word or text files. Java offers various methods for creating compressed or archive files when working with zip files. This tutorial will focus on demonstrating how to generate a zip file in Java.

Within the java.util.zip package, essential classes and interfaces are outlined for the creation of a zip file. This package encompasses not only components for ZIP format but also encompasses elements for the GZIP format. Moreover, included within the package are classes designed for both reading from and writing to zip files.

Using java.util.Zip Package

Prior to developing the Java application, it is essential to obtain the Apache Common Compress JAR file. Subsequently, establish a Java project and incorporate this JAR file into the project. Then, proceed by duplicating the Java program provided below and inserting it into the designated class file within the project.

CreateZipFile1.java

Example

import java.io.BufferedInputStream;

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;

public class CreateZipFile1

{

  static final int BUFFER = 1024;

  public static void main(String args[]) 

  {

//constructor of the ZipFile

   zipFile();

  }

  //method that create zip file

  private static void zipFile()

  {

    ZipOutputStream zos = null;

    BufferedInputStream bis = null;

    try

    {

      //path of the file that we want to compress

      String fileName = "C:\\Users\\Anubhav\\Desktop\\file1.txt";

      File file = new File(fileName);

      FileInputStream fis = new FileInputStream(file);

      bis = new BufferedInputStream(fis, BUFFER);      

      //creating ZipOutputStream

      //creates a zip file with the specified name

      FileOutputStream fos = new FileOutputStream("C:\\Users\\Anubhav\\Desktop\\demo.zip");

//ZipOutputStream writes data to an output stream in zip format

      zos = new ZipOutputStream(fos);                     

      // ZipEntry, here file name can be created using the source file

      ZipEntry ze = new ZipEntry(file.getName());

      //putting zipentry in zipoutputstream

      zos.putNextEntry(ze);

      byte data[] = new byte[BUFFER];

      int count;

      while((count = bis.read(data, 0, BUFFER)) != -1) 

      {

        zos.write(data, 0, count);

      }

    }

    catch(IOException ioExp)

    {

      System.out.println("Error while zipping " + ioExp.getMessage());

    }

    finally

    {

      if(zos != null)

      {

        try 

        {

        	//closing output stream

          zos.close();

        } 

        catch (IOException e) 

        {

          e.printStackTrace();

        }

      }

      if(bis != null)

      {

        try 

        {

        	//closing buffered input stream

          bis.close();

        } 

        catch (IOException e) 

        {

        //prints exception

          e.printStackTrace();

        }

      }

    }

  }

}

Let's compile and run the above program.

Output:

Upon creation, we can verify the existence of a zip archive matching the given name. To confirm the presence of the intended file, we will proceed to extract and examine its contents within the zip archive.

Zipping Multiple Files

ZippingMultipleFiles.java

Example

import java.io.BufferedInputStream;

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;

public class ZippingMultipleFiles 

{

  public static void main(String[] args) 

  {

    try 

    {

      //Source files

    String fileName1 = "C:\\Users\\Anubhav\\Desktop\\file1.txt";

      String fileName2 = "C:\\Users\\Anubhav\\Desktop\\file2.txt";

      //Zipped file

      String zipFilename = "C:\\Users\\Anubhav\\Desktop\\Allfiles.zip";

      File zipFile = new File(zipFilename);

      FileOutputStream fos  = new FileOutputStream(zipFile);            

      ZipOutputStream zos = new ZipOutputStream(fos);

      zipFile(fileName1, zos);

      zipFile(fileName2, zos);

      zos.close();

    } 

    catch (IOException e) 

    {

      e.printStackTrace();

    }

  }

  // Method to zip file

  private static void zipFile(String fileName, ZipOutputStream zos) throws IOException

  {

    final int BUFFER = 1024;

    BufferedInputStream bis = null;

    try

    {

      File file = new File(fileName);

      FileInputStream fis = new FileInputStream(file);

      bis = new BufferedInputStream(fis, BUFFER);          



      // ZipEntry --- Here file name can be created using the source file

      ZipEntry zipEntry = new ZipEntry(file.getName());        

      zos.putNextEntry(zipEntry);

      byte data[] = new byte[BUFFER];

      int count;

      while((count = bis.read(data, 0, BUFFER)) != -1) 

      {

        zos.write(data, 0, count);

      }  

      // close entry every time

      zos.closeEntry();

    } 

    finally

    {

      try 

      {

        bis.close();

      } 

      catch (IOException e) 

      {

        e.printStackTrace();

      }  

    }

  }

}

Output:

Zipping a Directory

Zipping a directory in Java can be achieved using a different method compared to the previous approach. There are two ways provided by Java to zip a directory:

  • Utilize the Files.walkFileTree method
  • Iterate through all files within the directory, add them to a list, and then proceed with the compression process.
  • Using Files.walkFileTree

  • Introduced in Java 7, the walkFileTree function is part of the Files class in the nio.file package. This function is employed for recursively compressing files, providing a concise and straightforward approach. It traverses through a directory tree.

Syntax:

Example

public static Path walkFileTree(Path start, FileVisitor<? super Path> visitor) throws IOException

It accepts two parameters:

start: It denotes the starting file.

visitor: Th file visitor to invoke each file.

The FileVisitor is an interface that acts as an argument for the method. To walk over a file tree, we need to implement a FileVisitor interface. It specifies the required behavior at key points in the traversal process that are:

  • When a file is visited
  • Before a directory is accessed
  • After a directory is accessed
  • When a failure occurs

Now, we will proceed with implementing the logic required to generate a compressed zip file for a specific directory.

ZippingDirectory.java

Example

import java.io.BufferedInputStream;

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 ZippingDirectory 

{

  static final int BUFFER = 1024;

  // Source folder which has to be zipped

  static final String FOLDER = "C:\\Users\\Anubhav\\Desktop\\demo folder";

  List<File> fileList = new ArrayList<File>();

  public static void main(String[] args) 

  {    

    ZippingDirectory zf = new ZippingDirectory();

    // get list of files

    List<File> fileList = zf.getFileList(new File(FOLDER));

    //go through the list of files and zip them 

    zf.zipFiles(fileList);    

  }

    

  private void zipFiles(List<File> fileList)

  {

    try

    {

      // Creating ZipOutputStream - Using input name to create output name

      FileOutputStream fos = new FileOutputStream(FOLDER.concat(".zip"));

      ZipOutputStream zos = new ZipOutputStream(fos);

      // looping through all the files

      for(File file : fileList)

      {

        // To handle empty directory

        if(file.isDirectory())

        {

          // ZipEntry --- Here file name can be created using the source file

          ZipEntry ze = new ZipEntry(getFileName(file.toString())+"/");

          // Putting zipentry in zipoutputstream

          zos.putNextEntry(ze);

          zos.closeEntry();

        }

        else

        {

          FileInputStream fis = new FileInputStream(file);

          BufferedInputStream bis = new BufferedInputStream(fis, BUFFER);

          // ZipEntry --- Here file name can be created using the source file

          ZipEntry ze = new ZipEntry(getFileName(file.toString()));

          // Putting zipentry in zipoutputstream

          zos.putNextEntry(ze);

          byte data[] = new byte[BUFFER];

          int count;

          while((count = bis.read(data, 0, BUFFER)) != -1) 

          {

              zos.write(data, 0, count);

          }

          bis.close();

          zos.closeEntry();

        }               

      }                

      zos.close();    

    }

    catch(IOException ioExp)

    {

      System.out.println("Error while zipping " + ioExp.getMessage());

      ioExp.printStackTrace();

    }

  }

    

 //the method returns a list of files

  private List<File> getFileList(File source)

  {      

    if(source.isFile())

    {

      fileList.add(source);

    }

    else if(source.isDirectory())

    {

      String[] subList = source.list();

      // this condition checks for empty directory

      if(subList.length == 0)

      {

        //System.out.println("path -- " + source.getAbsolutePath());

        fileList.add(new File(source.getAbsolutePath()));

      }

      for(String child : subList)

      {

        getFileList(new File(source, child));

      }

    }

    return fileList;

  }

    

  private String getFileName(String filePath)

  {

    String name = filePath.substring(FOLDER.length() + 1, filePath.length());

    //System.out.println(" name " + name);

    return name;      

  }

}

Output:

Input Required

This code uses input(). Please provide values below: