This article is about how to write a utility class for extracting files and directories in a compressed zip archive, using built-in Java API.

The java.util.zip package provides the following classes for extracting files and directories from a ZIP archive:

    • ZipInputStream: this is the main class which can be used for reading zip file and extracting files and directories (entries) within the archive. Here are some important usages of this class:
      • read a zip via its constructor ZipInputStream(FileInputStream)
      • read entries of files and directories via method getNextEntry()
      • read binary data of current entry via method read(byte)
      • close current entry via method closeEntry()
      • close the zip file via method close()

       

    • ZipEntry: this class represents an entry in the zip file. Each file or directory is represented as a ZipEntry object. Its method getName() returns a String which represents path of the file/directory. The path is in the following form:

      folder_1/subfolder_1/subfolder_2/…/subfolder_n/file.ext

       

Based on the path of a ZipEntry, we re-create directory structure when extracting the zip file.

In addition, the BufferedOutputStream class is used to write content of the current ZipEntry to a file on disk, via its method write(byte[] bytes, int offset, int length).

Following is source code of UnzipUtility.java class:

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * This utility extracts files and directories of a standard zip file to
 * a destination directory.
 * @author www.codejava.net
 *
 */
public class UnzipUtility {
    /**
     * Size of the buffer to read/write data
     */
    private static final int BUFFER_SIZE = 4096;
    /**
     * Extracts a zip file specified by the zipFilePath to a directory specified by
     * destDirectory (will be created if does not exists)
     * @param zipFilePath
     * @param destDirectory
     * @throws IOException
     */
    public void unzip(String zipFilePath, String destDirectory) throws IOException {
        File destDir = new File(destDirectory);
        if (!destDir.exists()) {
            destDir.mkdir();
        }
        ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
        ZipEntry entry = zipIn.getNextEntry();
        // iterates over entries in the zip file
        while (entry != null) {
            String filePath = destDirectory + File.separator + entry.getName();
            if (!entry.isDirectory()) {
                // if the entry is a file, extracts it
                extractFile(zipIn, filePath);
            } else {
                // if the entry is a directory, make the directory
                File dir = new File(filePath);
                dir.mkdirs();
            }
            zipIn.closeEntry();
            entry = zipIn.getNextEntry();
        }
        zipIn.close();
    }
    /**
     * Extracts a zip entry (file entry)
     * @param zipIn
     * @param filePath
     * @throws IOException
     */
    private void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
        byte[] bytesIn = new byte[BUFFER_SIZE];
        int read = 0;
        while ((read = zipIn.read(bytesIn)) != -1) {
            bos.write(bytesIn, 0, read);
        }
        bos.close();
    }
}

The UnzipUtility class has a public method for extracting files and directories from a zip archive:

    •           unzip(String zipFilePath, String destDirectory): extracts content of a zip file specified by zipFilePath to a directory specified by destDirectory.

 

And source code of a test class, UnzipUtilityTest.java:

/**
 
* A console application that tests the UnzipUtility class
 *
 * @author www.codejava.net
 *
 */
public class UnzipUtilityTest {
    public static void main(String[] args) {
        String zipFilePath = "e:/Test/MyPics.zip";
        String destDirectory = "f:/Pics";
        UnzipUtility unzipper = new UnzipUtility();
        try {
            unzipper.unzip(zipFilePath, destDirectory);
        } catch (Exception ex) {
            // some errors occurred
            ex.printStackTrace();
        }
    }
}

 

Related Java Zip File Tutorials:

 

Other Java File IO Tutorials:

 


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Attachments:
Download this file (UnzipUtility.java)UnzipUtility.java[utility class]1 kB
Download this file (UnzipUtilityTest.java)UnzipUtilityTest.java[test class]0.4 kB

Add comment

   


Comments 

#49Daniel2023-10-02 07:15
Worked for byte[] received from API. Thanks
Quote
#48Dilip2022-02-01 16:46
the code worked as it was!
Quote
#47Harold Burton2021-10-08 01:45
I tried to extend HDD Size of Guest machine running on Windows Server 2003 from 14 GB to 80 GB using ""vmware-vdiskmanager -x 80GB "". got and erroC:\Program Files\VMware\VMware Workstation>vmware-vdiskmanager.exe -x 70GB ""e:\VM\Test.vmdk"" Grow: 100% done.Failed to expand the disk 'e:\VM\Test.vmdk': The file already exists (0x270000000c)Created a tmp file like ""Test.vmdk.dsfghi.tmp"" in same folder with same size[14 GB]

Harold Burton
Quote
#46Joseph Donahue2021-08-13 00:47
I create a share on my HyperV server so that u can write to it via my workstation. Before I create a VM I copy the proper iso to the hyperV server. I can then have a central download area for iso images and copy them around as needed. I typically don't load iso images from a share because any network blip will crash the create process. It is always best to have them local.
Joseph Donahue
Quote
#45Kailash2021-05-17 13:15
Thanks Minh, very short and fully functional code. I used it in my linux envrionment.
Quote