Skip to content
Related Articles

Related Articles

Create Password Protected Zip File in Java
  • Last Updated : 03 Mar, 2021

Primarily, java does not have any function or package that will create a password-protected zip file without using some native codes. Java has some useful library which is good but they use some native codes to perform their task that makes their usage platform dependent to some extent. Whereas in the zip4j library we are just using java code without any support of native code, that is the reason that people are using jip4j over other built-in libraries. 

There is a library called ‘zip4j’ which was written by “Srikanth Reddy Lingala” back in 2008/2009. It is the most comprehensive Java library for zip files.

Some important features of the zip4j library are as follows:

  1. It will create, add, extract, update, remove files from a zip file.
  2. It has support for streams like ZipInputStream and ZipOuputStream.
  3. We can use this library to create any password-protected zip file in java.
  4. We can zip/unzip any existing file or directory by just specifying the file path.
  5. It also provides supports for both AES 128/256 Encryption and standard Zip Encryption.

Note: ‘zip4j’ is written on JDK 8 and if we try to run this library on JDK 7, then not all features will be supported.

Methods:



  1. Naive approach using java.util.zip package
  2. Efficient approach

Method 1: Naive approach 

We don’t have any standard java in-built library to create a password-protected zip file. We can only make a simple zip file with the help of the java.util.zip package.

Example

Java




// Java Program to Create Password Protected Zip File
  
// Importing all input output classes
import java.io.*;
// Importing java.nio utility package API
// used for manipulating files and directories
// mostly working on Path object
import java.nio.file.*;
// Importing all zip classes from
// java.util package 
import java.util.zip.*;
  
// Class 
// Main class 
public class ZipFile {
  
// Method 1 
 // Creating an existing file as a zip file
    private static void zipFile(String filePath) {
          
        // Try block  to check if any excrption occurs 
        try {
  
            // Creating an object of File type
            // getting filePath by passing as an argument
            File file = new File(filePath);
  
            // Getting the name of the above file
            // as an ZIP format 
            String zipFileName = file.getName().concat(".zip");
              
            // Creating FileOutputStream object and passing the
            // zip file as an argument
            FileOutputStream fos = new FileOutputStream(zipFileName);
  
            // Creating sn object of FileOutputStream and
            // passing the above object as an argument
            ZipOutputStream zos = new ZipOutputStream(fos);
              
            zos.putNextEntry(new ZipEntry(file.getName()));
   
            // Writing the ZipEntry to stream is not enough
            // as we need to write its content as well
            // using the putNextEntry() method
            byte[] bytes = Files.readAllBytes(Paths.get(filePath));
            zos.write(bytes, 0, bytes.length);
              
            // ZipFile can only hold 1 entry sream at a go, &
            // if another entry is to be passed then
            // current entry stream has to be closed closeEntry
  
            // Closing the current entry stream
            // using the closeEntry() method
            zos.closeEntry();
  
            // Closing the entire stream completely
            zos.close();
  
        // If file dose not find then it will return the file does not exist
        }
          
        // Catch block 1 
        // Catch block to handle FieNotFoundException
        catch (FileNotFoundException ex) {
  
            // Print and display message
            System.err.format("The file does not exist", filePath);
        
  
        // Catch block 2
        // Catch block to handle input output exception
        catch (IOException ex) {
  
            // Print and display message  
            System.err.println("ERROR: " + ex);
        }
    }
   
    // Method 2
    // Main driver method
    public static void main(String[] args) {
          
        String filePath = args[0];
          
        // Calling the above method 1
        zipFile(filePath);
  
    }
}

Method 2: Efficient approach

Procedure:

  1. First, create a list of files to be added to the ZIP file and
  2. Specifying the path you can add it to the list.

Example

Java




// Java Program to Create Password Protected Zip File
  
// Importing required  libraries
// Here, lingala is the name of men 
// who created zip4j library
import java.io.File;
import java.util.ArrayList;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
  
// Class
// To create password protected ZIP file
public class GFG {
  
    // Main driver method
    public static void main(String[] args) {
              
           // Try block to check if any exception occurs
           try {
   
                  // Creating encryption zipParameters
                  // for passward protection
                  ZipParameters zipParameters = new ZipParameters();
   
                  // Setting encryption files
                  zipParameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
                  zipParameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
   
                  // Setting encryption of files to true
                  zipParameters.setEncryptFiles(true);
   
                  // Setting encryption method
                  zipParameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
                    
                  // Set the key strength
                  zipParameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
   
                  // Set the password
                  zipParameters.setPassword("password");
   
               
                  // *********CREATE ZIP FILE***************
   
                  //Zip file name
                  String destinationZipFilePath = "D:/myZipFile.zip";
                    
                  // Creating ZIP file 
                  ZipFile zipFile = new ZipFile(destinationZipFilePath);
   
                  // Creating list of files to be added to ZIP file
                  ArrayList<File> list = new ArrayList<File>();
                  //Add SPECIFIC  files
                  list.add(new File("D:/myFile1.txt"));
                  list.add(new File("D:/myFile2.txt"));
   
                  // Pass and ZIP parameters
                  // for Zip file to be created
                  zipFile.addFiles(list, zipParameters);
   
                  // Print the destination in the local directory 
                  // where ZIP file is created
                  System.out.println("Password protected Zip file"
                               + "have been created at "  + destinationZipFilePath);
              
            // Catch block to handle the exceptions
           } catch (ZipException e) {
  
                  // Print the exception and line number
                  // where tit occured  
                  e.printStackTrace();
           }
    }
}

Output: After running this code password-protected Zip file of specific files has been created at D:/myZipFile.zip.



Output explanation:

Before execution in the above image, we can see 1 directory and 2 files named GeeksForGeeks.txt and krishana_97

Now after execution, we can see the new zip file created. This zip file is the password protested zip file. You have to give the correct password to access the file inside this zip.

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :