Sunday, March 21, 2021

How to Create Password Protected Zip File in Java

This post shows how to create a password protected zip file in Java and also how to unzip a password protected zip file in Java.

Though Java provides an API (java.util.zip) for compressing and decompressing files in zip format but there is no option for setting password so you need to use a third party library for creating a password protected zip file.

Library used here is Zip4j. You can download the jar zip4j_1.3.2.jar from here- http://www.lingala.net/zip4j/download.php. Ensure that it is added to your application’s class path.

You can also add the following Maven dependency to download the jars.

<dependency>
    <groupId>net.lingala.zip4j</groupId>
    <artifactId>zip4j</artifactId>
    <version>2.6.2</version>
</dependency>

Zipping and unzipping password protected file in Java

In the code there are two methods compressWithPassword() and unCompressPasswordProtectedFiles(). compressWithPassword() method is used to create a password protected zipped file where as unCompressPasswordProtectedFiles() method is used to unzip a password protected zipped file.

Directory structure that is used for zipping has the structure as following.

files
--Empty Folder
--test
   sub.txt
 bus.txt

Parent folder is files, with in that there are two sub-folders Empty Folder and test, inside test there is one file sub.txt and at the parent level there is one file bus.txt.

 
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;

public class PasswordProtectedZipDemo {

 public static void main(String[] args) {
  
  PasswordProtectedZipDemo pzip = new PasswordProtectedZipDemo();
  try {
   pzip.compressWithPassword("G:\\files");
  } catch (ZipException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  /*try {
   pzip.unCompressPasswordProtectedFiles("G:\\files.zip");
  } catch (ZipException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }*/
 }
 
 /**
  * Method for creating password protected zip file
  * @param sourcePath
  * @throws ZipException
  */
 private void compressWithPassword(String sourcePath) throws ZipException{
 
  String destPath = sourcePath + ".zip";
  System.out.println("Destination " + destPath);
  ZipFile zipFile = new ZipFile(destPath);
  // Setting parameters
  ZipParameters zipParameters = new ZipParameters();
  zipParameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
  zipParameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_ULTRA);
  zipParameters.setEncryptFiles(true);
  zipParameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
  zipParameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
  // Setting password
  zipParameters.setPassword("pass@123");
       
  zipFile.addFolder(sourcePath, zipParameters);
 }
 
 /**
  * Method for unzipping password protected file
  * @param sourcePath
  * @throws ZipException
  */
 private void unCompressPasswordProtectedFiles(String sourcePath) throws ZipException{
  String destPath = getFileName(sourcePath);
  System.out.println("Destination " + destPath);
  ZipFile zipFile = new ZipFile(sourcePath);
  // If it is encrypted then provide password
  if(zipFile.isEncrypted()){
   zipFile.setPassword("pass@123");
  }
  zipFile.extractAll(destPath);
 }
 
 private String getFileName(String filePath){
  // Get the folder name from the zipped file by removing .zip extension
  return filePath.substring(0, filePath.lastIndexOf("."));
 }
}

If you want to zip specific file then you can add them in an Arraylist as File object and pass that list to the addFiles() method.

Java code

 
private void compressFiles() throws ZipException{
  ZipFile zipFile = new ZipFile("G:\\test.zip");
  ArrayList<File> fileList = new ArrayList<File>();
  fileList.add(new File("G:\\abc.txt"));
  fileList.add(new File("G:\\files\\bus.txt"));
  // Setting parameters
  ZipParameters zipParameters = new ZipParameters();
  zipParameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
  zipParameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_ULTRA);
  zipParameters.setEncryptFiles(true);
  zipParameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
  zipParameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
  // Setting password
  zipParameters.setPassword("pass@123");
  
  zipFile.addFiles(fileList, zipParameters);
}

That's all for this topic How to Create Password Protected Zip File in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Compress And Decompress File Using GZIP Format in Java
  2. Creating Tar File And GZipping Multiple Files in Java
  3. How to Untar a File in Java
  4. Java Program to Convert a File to Byte Array
  5. Reading Delimited File in Java Using Scanner

You may also like-

  1. Java Program to Find The Longest Palindrome in a Given String
  2. Find Largest and Second Largest Number in Given Array Java Program
  3. How to Display Time in AM-PM Format in Java
  4. How to Run a Shell Script From Java Program
  5. Marker Interface in Java
  6. Transaction Management in Java-JDBC
  7. Serialization Proxy Pattern in Java
  8. Why wait(), notify() And notifyAll() Methods Are in Object Class And Not in Thread Class