Java has an excellent in-built Zip support but it lacks several Zip functionalities (ex: support for encrypted Zip files, etc). So in this post, I using opensource java library on top of Java’s inbuit Zip functionality that can support most of the Zip format specifications. Zip4j is a simple to use, opensource java library that supports creating, extracting, updating Zip files. It supports Standard Zip encryption and AES encryption for Zip files, Zip64 format, etc. Now, lets start to see how easy to zip file(s) and extract it with Zip4j.

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

/**
 *
 * @author EtaYuy88 aka Meihta Dwiguna Saputra
 */
public class Zip {
    //create zip
    public void create(String filePath, String zipPath)
    {
        try {
            //zipPath is absolute path of zipped file
            ZipFile zipFile = new ZipFile(zipPath);
            //filePath is absolute path of file that want to be zip
            File fileToAdd = new File(filePath);
            //create zip parameters such a password, encryption method, etc
            ZipParameters parameters = new ZipParameters();
            parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
            parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
            parameters.setEncryptFiles(true);
            parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD);
            parameters.setPassword("mdsaputra");
            zipFile.addFile(fileToAdd, parameters);
        } catch (ZipException e) {
            e.printStackTrace();
        }
    }//end of create zip

    //extract zip file
    private void extract(zipPath,extractPath) throws ZipException
    {
        ZipFile zipFile = new ZipFile(zipPath,extractPath);
        // Check to see if the zip file is password protected
        if (zipFile.isEncrypted())
        {
        // if yes, then set the password for the zip file
            zipFile.setPassword("mdsaputra");
        }
        //extractPath is absolute path of file after extracted
        zipFile.extractAll(extractPath);
    }//end of extract

}

If you want to put more than one file inside the zip, you can simply just make list of files then add it when create the zip file. By the way zip4j can be download in this link. Simple and easy isn’t? Hope this post help you 😉 and to let you know about my newest post, don’t forget to