Java program to zip and unzip files

Java program to zip and unzip files

The java.util.zip package provides classes for reading and writing the standard ZIP and GZIP file formats. With this package you will be able to compress files to ZIP format and extract or decompress files from a given ZIP file. In this post we will see Java program to zip and unzip files. We will see example Java programs using ZIP library in Java SDK and also using a third party library called Zip4j.

Java program to zip files

ZipOutputStream is the main class for writing files in the ZIP file format.

ZipFileExample.java

Here is the screenshot of the zip file created by the above program.

zip file

 

Java program to recursively zip files inside directory

In this program we will recursively read all files from folder D:\\testzip and compress it into a zip file – D:\\MyZipFile.zip.

The directory structure of testzip folder is as follows.

directory structure

ZipDirectoryExample.java

Below is the output of running the above program.

Java program to unzip files

ZipInputStream is the main class which can be used for reading zip file and extracting files and directories (entries) within the archive. We will unzip the zip file  – D:\\MyZipFile.zip created by the previous program.

UnzipFileExample.java

Here is the output of the above program.

As seen from the output, the output directory is created with the same directory structure as of the input zip file.

Unzip files using third party library Zip4j

You can download the latest version of Zip4j library here. The code for unzipping files using Zip4j is very simple. It contains only few lines of code.

UnZip4jExample.java

After running the above program, you will see that the output directory is created with the same directory structure as of the input zip file.

Zip files using third party library Zip4j

Zip4jExample.java

After running the above program, the testzip folder will be compressed and Zip4jZipFile.zip file will be created in the D drive. All the files inside the zip archive are password protected. Similarly text.txt file will be compressed into Zip4jZipFile1.zip file. The file inside the archive will be password protected.

Hope you have learnt how to compress and decompress zip files using in-built library in JDK and also using the third party library Zip4j. If you have any comments, post it in the comments section.

Additional Resource

Compressing and Decompressing Data Using Java APIs

 

The following two tabs change content below.
Working as a Java developer since 2010. Passionate about programming in Java. I am a part time blogger.

Add Comment

Required fields are marked *. Your email address will not be published.