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.
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.
Let's compile and run the above program.
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.
Zipping Multiple Files
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:
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:
Let's implement the logic to create a zip file for a directory.