Creating Password Protected Zip File in Java

In the post how to zip files in Java and how to zip a folder in Java we have already seen how to compress files and directories in Java. In this post we’ll see how to create a password protected zip file in Java and how to unzip a password protected compressed file.

Password protected zip file support in Java

With in the java.util.zip package which includes classes for compressing and decompressing files there is no support for creating password protected zip files therefore Zip4j library is used for the purpose.

Jar that is needed for creating password protected zip files- zip4j_1.3.2.jar can be downloaded from this location – http://www.lingala.net/zip4j/download.php.

Though Zip4j library is a bit old and there are other available options but in my opinion this library is sill the best bet for creating password protected zip files.

Password protected zip file Java example

Two examples given here cover the scenario where you have separate files which you can add to folder then compress and password protect it.
Another scenario is when you want to compress a directory and password protect it. We’ll also see how to unzip a password protected file.

Add files to folder and compress

If you want to compress separate files then add them to an ArrayList and pass that list along with the parameters for compression and encryption to get a password protected zipped file. In the example, unZipPasswordProtectedFiles() method unzips the password protected zipped file.

Zip whole directory with password protection

If a directory structure has to be compressed recursively then you can do it as given here. Directory structure which is compressed in the example is as given below.

password protected zip file

You can see how unzipping a zipped directory requires a password.

password protected zip file java

That’s all for the topic Creating Password Protected Zip File in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.