How to Zip a file using Java

Sometimes it may happen that the in your application the size of log files increases and you have to run to your infrastructure team to either archive them or add more space to your configurations. Its always wise to plan ahead and make sure that your logs are archived periodically so you save on space and some late night support calls :). In this article we will see how to zip a file using Java.

Java has inbuilt support to perform ZIP compression. You can access the Java library here. In this article we will go over small utility that you can use to zip or unzip a files from particular directory. The flow for this is simple. The java library provides necessary classes for that. First you need to create ZipEntry and then output the same to ZipOutputStream

ZIP files from a directory

First we will see how we can zip all the text files from a directory.

You can see the we are expecting the list of files to be archived and the complete path for destination zip file. We are simply iterating over those files and creating zipentry for that. Then we read that file and writer to ZipOutputStream.

Please observe that I am using settime method of zipentry. That is required if you want to preserver the file modified timestamp.

Below is our function that gives us the list of files that fits the zip criteria. It filters out files based on extension.

For our testing purpose we are not doing recursive directory listing. But that can be easily achieved in this function based on a check if particular entry is file or directory.

Unzip files from zipped archive

Now we have seen how to zip a file in above code snippet,  we will also see how we can unzip the archive and retrieve files. The process is exactly opposite. Here we need to read the zip using ZipInputStream and read all the ZipEntries in it. Then these zipentries are read and transferred to corresponding new files.

And here is the simple usage

How to zip a File using Java

How to zip a File using Java

Output

You can download the complete code from our GitHub Repository

Download from Git

Add a Comment

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