Zipping and Unzipping Nested Directories in Java using Apache Commons Compress (Zip Unzip Files & Folders Recursively)

I've been looking for a Java library on the Internet to compress and decompress a directory recursively for awhile now and haven't been able to find anything. It's strange in this day and age that something like this doesn't exist, and that so many developer's around the world are having to reinvent the wheel. Oh well, the code to do it shown below. You'll need to grab a copy of Apache Commons Compress and Commons Logging (the links are below the code).


Overview Of Apache Commons And Why You Should Be Using It

Apache Commons is a set of high level libraries developed to help you with your everyday work. It is your Bat Utility Belt of tools that you'll need to get the job done faster, more efficiently, and with less bugs. It provides frequently needed libraries that will save you from having to roll your own every time. By using them, you will save time and money. An excellent book on the subject is Jakarta Commons Cookbook

When you start out with Apache Commons, I would start by getting familiar with the following basic libraries:

  • Lang - for commons everyday tasks that some argue should have been built into the language. These include classes to help with String manipulation, Enums, and Reflection etc
  • Collections - helper utility with tons of common shortcuts for working with Collections
  • Email - for easily sending HTML formatted email with multiple attachments


Once you realize the benefits they provide, I would then start to explore these additional libraries for more specific tasks:

  • BeanUtils - for manipulating objects using Reflection.
  • Compress - for handling different types of compression formats, including tar, zip and bzip2
  • Configuration - for reading property and config files of various formats
  • CSV - work with CSV data
  • DBUtils - JDBC helper library
  • Exec - to help run processes outside the JVM. eg. Helps run UNIX or DOS commands
  • Id - id generator
  • IO - collection of IO utilities
  • Launcher - Java application launcher
  • Logging - work with various logging frameworks with a single interface
  • Math - Math and statistics libraries
  • Net - Internet protocol suite
  • Pipeline - libraries for working with queues
  • Primitives - improved classes for working with primitive data types
  • Transaction - Allows you to work with files, collections, etc using transactions


For large development projects, the following libraries provide some seriously powerful functionality:

  • Attributes - for working with annotations
  • Betwixt - for mapping JavaBeans to XML
  • Codec - provides a basis for writing compression/decompression algorithms
  • Daemon - provides UNIX daemon-like functionality
  • DBCP - connection pooling to improve the responsiveness of database calls
  • Finder - provides Unix 'find' functionality
  • JavaFlow - captures the state of an entire application
  • Monitoring - monitor the performance of threads.
  • Performance - framework for MicroBench clients
  • Pool - Object caching library
  • Proxy - dynamic proxy management
  • Validator - XML data validation framework
  • VFS - virtual file system.


If you're not using these library components, your doing a lot more work than you need to, taking longer to do it, and introducing more bugs than are necessary.

NOTE: If you want to develop your Java skills fast, I would definitely recommend getting one of the books on Apache Commons to help get you up to speed. Seeing the code used to solve real-world problems is undoubtedly the best way of learning the various Apache Commons libraries, rather that looking at the API's and trying to figure out where and how they could help you.

 

 

package main.util;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.util.Enumeration;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.apache.commons.compress.utils.IOUtils;

/**
 * Utility to Zip and Unzip nested directories recursively.
 * @author Robin Spark
 */
public class ZipUtil {

    /**
     * Creates a zip file at the specified path with the contents of the specified directory.
     * NB:
     *
     * @param directoryPath The path of the directory where the archive will be created. eg. c:/temp
     * @param zipPath The full path of the archive to create. eg. c:/temp/archive.zip
     * @throws IOException If anything goes wrong
     */
    public static void createZip(String directoryPath, String zipPath) throws IOException {
        FileOutputStream fOut = null;
        BufferedOutputStream bOut = null;
        ZipArchiveOutputStream tOut = null;

        try {
            fOut = new FileOutputStream(new File(zipPath));
            bOut = new BufferedOutputStream(fOut);
            tOut = new ZipArchiveOutputStream(bOut);
            addFileToZip(tOut, directoryPath, "");
        } finally {
            tOut.finish();
            tOut.close();
            bOut.close();
            fOut.close();
        }

    }

    /**
     * Creates a zip entry for the path specified with a name built from the base passed in and the file/directory
     * name. If the path is a directory, a recursive call is made such that the full directory is added to the zip.
     *
     * @param zOut The zip file's output stream
     * @param path The filesystem path of the file/directory being added
     * @param base The base prefix to for the name of the zip file entry
     *
     * @throws IOException If anything goes wrong
     */
    private static void addFileToZip(ZipArchiveOutputStream zOut, String path, String base) throws IOException {
        File f = new File(path);
        String entryName = base + f.getName();
        ZipArchiveEntry zipEntry = new ZipArchiveEntry(f, entryName);

        zOut.putArchiveEntry(zipEntry);

        if (f.isFile()) {
            FileInputStream fInputStream = null;
            try {
                fInputStream = new FileInputStream(f);
                IOUtils.copy(fInputStream, zOut);
                zOut.closeArchiveEntry();
            } finally {
                IOUtils.closeQuietly(fInputStream);
            }

        } else {
            zOut.closeArchiveEntry();
            File[] children = f.listFiles();

            if (children != null) {
                for (File child : children) {
                    addFileToZip(zOut, child.getAbsolutePath(), entryName + "/");
                }
            }
        }
    }

    /**
     * Extract zip file at the specified destination path. 
     * NB:archive must consist of a single root folder containing everything else
     * 
     * @param archivePath path to zip file
     * @param destinationPath path to extract zip file to. Created if it doesn't exist.
     */
    public static void extractZip(String archivePath, String destinationPath) {
        File archiveFile = new File(archivePath);
        File unzipDestFolder = null;

        try {
            unzipDestFolder = new File(destinationPath);
            String[] zipRootFolder = new String[]{null};
            unzipFolder(archiveFile, archiveFile.length(), unzipDestFolder, zipRootFolder);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Unzips a zip file into the given destination directory.
     *
     * The archive file MUST have a unique "root" folder. This root folder is 
     * skipped when unarchiving.
     * 
     * @return true if folder is unzipped correctly.
     */
    @SuppressWarnings("unchecked")
    private static boolean unzipFolder(File archiveFile,
            long compressedSize,
            File zipDestinationFolder,
            String[] outputZipRootFolder) {

        ZipFile zipFile = null;
        try {
            zipFile = new ZipFile(archiveFile);
            byte[] buf = new byte[65536];

            Enumeration entries = zipFile.getEntries();
            while (entries.hasMoreElements()) {
                ZipArchiveEntry zipEntry = entries.nextElement();
                String name = zipEntry.getName();
                name = name.replace('\\', '/');
                int i = name.indexOf('/');
                if (i > 0) {
                        outputZipRootFolder[0] = name.substring(0, i);
                    }
                    name = name.substring(i + 1);
                }

                File destinationFile = new File(zipDestinationFolder, name);
                if (name.endsWith("/")) {
                    if (!destinationFile.isDirectory() && !destinationFile.mkdirs()) {
                        log("Error creating temp directory:" + destinationFile.getPath());
                        return false;
                    }
                    continue;
                } else if (name.indexOf('/') != -1) {
                    // Create the the parent directory if it doesn't exist
                    File parentFolder = destinationFile.getParentFile();
                    if (!parentFolder.isDirectory()) {
                        if (!parentFolder.mkdirs()) {
                            log("Error creating temp directory:" + parentFolder.getPath());
                            return false;
                        }
                    }
                }

                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(destinationFile);
                    int n;
                    InputStream entryContent = zipFile.getInputStream(zipEntry);
                    while ((n = entryContent.read(buf)) != -1) {
                        if (n > 0) {
                            fos.write(buf, 0, n);
                        }
                    }
                } finally {
                    if (fos != null) {
                        fos.close();
                    }
                }
            }
            return true;

        } catch (IOException e) {
            log("Unzip failed:" + e.getMessage());
        } finally {
            if (zipFile != null) {
                try {
                    zipFile.close();
                } catch (IOException e) {
                    log("Error closing zip file");
                }
            }
        }

        return false;
    }

    private static void log(String msg) {
        System.out.println(msg);
    }

    /**
     * Method for testing zipping and unzipping.
     * @param args 
     */
    public static void main(String[] args) throws IOException {
        createZip("c:/temp/99/target", "c:/temp/99/output2.zip");
        extractZip("c:/temp/99/output2.zip", "c:/temp/99/1");
    }
}

Comments 6 comments

Joe The Plumber 4 years ago

Thanks for sharing, but in the "addFileToZip" method, you have to fix this or else open handlers on files are left at the end of the process:

Change this:

---------------------------

IOUtils.copy(new FileInputStream(f), zOut);

zOut.closeArchiveEntry();

---------------------------

Into this:

---------------------------

FileInputStream fInputStream = null;

try {

fInputStream = new FileInputStream(f);

IOUtils.copy(fInputStream, zOut);

zOut.closeArchiveEntry();

} finally {

IOUtils.closeQuietly(fInputStream);

}

---------------------------


Shankar 4 years ago

Good Job, Thanks, I did few changes to make it workable for me.

Small typo mistake in the program. at line 126 if (i 0) { 'greater than' is missing.

name = name.substring(i + 1); no need of this line. It working after commenting the line.

fis is not closed...


Steven 4 years ago

I cannot thank you enough!! Great reference for me!! I had some problems implementing your code so here is what I ended up doing that seems to work for any zip I have tested it with thus far:

package com.homedepot.mm.sv.large_unzip_util;

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.text.DateFormat;

import java.text.SimpleDateFormat;

import java.util.Date;

import org.apache.commons.compress.archivers.ArchiveException;

import org.apache.commons.compress.archivers.ArchiveInputStream;

import org.apache.commons.compress.archivers.ArchiveStreamFactory;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;

import org.apache.commons.compress.utils.IOUtils;

/**

* Utility to Zip and Unzip nested directories recursively.

*/

public class LargeUnzipUtilForDSE {

/**

* Method for testing zipping and unzipping.

* @param args

*/

public static void main(String[] args) throws IOException {

/*

* remove comment for local testing:

*/

/*

String zipName = "C:/Users/Desktop/Unzipping Jar/Zips For Testing/Zip1.zip";

String outputDirName = "C:/Users/Desktop/Unzipping Jar/";

unzipper(zipName, outputDirName);

*/

/*

* END - remove comment for local testing

/*

/*

* Comment out for local testing:

*/

String zipName = args[0];

String outputDirName = args[1];

System.out.println("**The Zip file read in is: " + zipName);

System.out.println("**The output path for the zip read in is: " + outputDirName);

/*

* END - Comment out for local testing

*/

unzipper(zipName, outputDirName);

}

public static void unzipper(String input, String dir){

//Initializing the date variable in a easy to read format:

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

//get current date time with Date()

Date date1 = new Date();

System.out.println("**Unzip Execution started at " + dateFormat.format(date1));

try{

FileInputStream fin = new FileInputStream(input);

final BufferedInputStream is = new BufferedInputStream(fin);

BufferedOutputStream out = null;

ZipArchiveEntry entry = null;

File fileEntry = null;

ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("zip", is);

if(in != null){

entry = (ZipArchiveEntry)in.getNextEntry();

}

//looping until there are no more zip files

while (entry != null) {

//checking if the entry in the archive is a directory and acting on it appropriately

int i = 1;

while (i == 1){

fileEntry = new File(dir, entry.getName());

//checking if the archive entry is a directory as if it is, it will end with a / or a \

String strEntry = entry.getName();

//ensuring the slashes are read in as forward slashes since java doesn't like backslashes:

strEntry = strEntry.replace('\\', '/');

//quickly checking if the current entry is a directory (in this "if" and "else if"):

if (strEntry.endsWith("/") && !fileEntry.exists()){

//if the directory does not exist, then create it

System.out.println("Creating directory: " + fileEntry);

fileEntry.mkdirs();

//now grab the next entry in the archive

entry = (ZipArchiveEntry)in.getNextEntry();

strEntry = entry.getName();

strEntry = strEntry.replace('\\', '/');

}

else if (strEntry.endsWith("/") && fileEntry.exists()){

//if the directory already exists, then simply move on to the next entry in the archive

System.out.println("This directory already exists: " + fileEntry);

entry = (ZipArchiveEntry)in.getNextEntry();

fileEntry = new File(dir, entry.getName());

strEntry = entry.getName();

strEntry = strEntry.replace('\\', '/');

}

//check to see if the next entry is a directory (this mainly applies if the above two if blocks were used:

if (strEntry.endsWith("/")){

System.out.println("The next entry in the archive is a directory:" + entry.getName());

i = 1;

}

else{

/*

* **More thorough directory checking (slower but necessary to account for all archive formats)**

*

* need to check if the last folder name is already created and create it if it is not

* when zipped differently this is how it can show up in the strEntry: testing/file.ver

* and is why we need to perform this check as well

*/

/*grabbing the last place where / exists as everything before that will be directories that

must be created if they do not already exist: */

int slash = strEntry.lastIndexOf('/');

String folderName = "";

//replace "greater than or equal to" below with the correct syntax, since I cannot post those characters here

if (slash "greater than or equal to" 0) {

//grab the folder names before the last /

folderName = strEntry.substring(0, slash);

//grab the file name after the last /

strEntry = strEntry.substring(slash + 1);

//append the passed in directory to the folderNames read from the archive:

File fileFolderName = new File(dir + "/" + folderName);

System.out.println("Current working directory name = " + fileFolderName);

System.out.println("Current file name = " + strEntry);

if (!fileFolderName.exists()){

//if the directory(s) do not exist then create them

System.out.println("Creating directory: " + folderName);

fileFolderName.mkdirs();

}

}

System.out.println("The next entry in the archive is NOT a directory:" + entry.getName());

i = 0;

//since the entry in the archive is not a directory we need to add it to the output stream:

if (entry != null){

FileOutputStream fos = new FileOutputStream(new File(dir, entry.getName()));

out = new BufferedOutputStream(fos);

}//END - if

}//END - else

}//END - while

if (entry != null){

System.out.println("Unzipping: " + entry.getName());

//unzipping the file inside of the out output stream:

IOUtils.copy(in, out);

//grabbing the next entry in the archive

entry = (ZipArchiveEntry)in.getNextEntry();

System.out.println("Next Entry to unzip from the archive: " + entry);

}

else{

//if the entry is null that means we are done with the archive, thus breaking:

break;

}

}

if (out != null){

out.close();

}

if (in != null){

in.close();

}

}

catch (IOException e) {

e.printStackTrace();

}

catch (ArchiveException i) {

i.printStackTrace();

}

//Initializing the date variable in a easy to read format:

dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

//get current date time with Date()

date1 = new Date();

System.out.println("**Unzip Execution finished at " + dateFormat.format(date1));

}//end unzipper

}//end class


Steven 4 years ago

*****VERY IMPORTANT*****

Do NOT use the previous code that I pasted, as it will CORRUPT your unzipped files!!!!!

Instead take off the buffered stuff and just use normal file readers and everything will work as expected.


Johne138 16 months ago

Several of these games are worth some time and are actually egefaedeeebb


Johnb927 15 months ago

Great blog! I am loving it!! Will come back again. I am taking your feeds also bffgaekbgecd

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working