How to Create Zip File in Java?

In Java, working with zip file is not the same as working with word file or text file. In the context of zip file Java provides different ways to create zip or compressed or archive file. In this section, we will learn how to create zip file in Java.

The necessary classes and interfaces that are required to create a zip file are defined in java.util.zip package. The package does not only provide classes for ZIP format but also provides classes for the GZIP format. The package also provides the classes to read from and write to the zip file.

How to Create Zip File in Java

Using java.util.Zip Package

Before creating the Java program, first we need to download the apache common compress JAR file. Now create a Java project and add this JAR file to the project. Copy the following Java program and paste it in the class file that you have created.

CreateZipFile1.java

Let's compile and run the above program.

Output:

How to Create Zip File in Java

We observe that a zip file with the specified name is created. Let's open the zip file and see the specified file added to zip file or not.

How to Create Zip File in Java

Zipping Multiple Files

ZippingMultipleFiles.java

Output:

How to Create Zip File in Java

Zipping a Directory

Create a zip of a directory is a bit different form the above approach. Java provides two way to zip a directory:

  • Use Files.walkFileTree() Method
  • Read all files from the folder and add that files to list, then perform compression.

Using Files.walkFileTree()

  • The method walkFileTree() is presented since Java 7. It is defined in the Files class that resides in the nio.file package. It is used to reclusively zip the file. It makes code short and simple. The method walks over a file tree.

Syntax:

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

Let's implement the logic to create a zip file for a directory.

ZippingDirectory.java

Output:

How to Create Zip File in Java