// Tutorial //

Java Unzip File Example

Published on August 3, 2022
Default avatar
By Pankaj
Developer and author at DigitalOcean.
Java Unzip File Example

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Welcome to Java Unzip File Example. In the last post, we learned how to zip file and directory in java, here we will unzip the same zip file created from directory to another output directory.

Java Unzip File

To unzip a zip file, we need to read the zip file with ZipInputStream and then read all the ZipEntry one by one. Then use FileOutputStream to write them to file system. We also need to create the output directory if it doesn’t exists and any nested directories present in the zip file. Here is the java unzip file program that unzips the earlier created tmp.zip to output directory.

package com.journaldev.files;

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;

public class UnzipFiles {

    public static void main(String[] args) {
        String zipFilePath = "/Users/pankaj/tmp.zip";
        
        String destDir = "/Users/pankaj/output";
        
        unzip(zipFilePath, destDir);
    }

    private static void unzip(String zipFilePath, String destDir) {
        File dir = new File(destDir);
        // create output directory if it doesn't exist
        if(!dir.exists()) dir.mkdirs();
        FileInputStream fis;
        //buffer for read and write data to file
        byte[] buffer = new byte[1024];
        try {
            fis = new FileInputStream(zipFilePath);
            ZipInputStream zis = new ZipInputStream(fis);
            ZipEntry ze = zis.getNextEntry();
            while(ze != null){
                String fileName = ze.getName();
                File newFile = new File(destDir + File.separator + fileName);
                System.out.println("Unzipping to "+newFile.getAbsolutePath());
                //create directories for sub directories in zip
                new File(newFile.getParent()).mkdirs();
                FileOutputStream fos = new FileOutputStream(newFile);
                int len;
                while ((len = zis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
                }
                fos.close();
                //close this ZipEntry
                zis.closeEntry();
                ze = zis.getNextEntry();
            }
            //close last ZipEntry
            zis.closeEntry();
            zis.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }

}

Once the program finishes, we have all the zip file contents in the output folder with same directory hierarchy. Output of the above program is:

Unzipping to /Users/pankaj/output/.DS_Store
Unzipping to /Users/pankaj/output/data/data.dat
Unzipping to /Users/pankaj/output/data/data.xml
Unzipping to /Users/pankaj/output/data/xmls/project.xml
Unzipping to /Users/pankaj/output/data/xmls/web.xml
Unzipping to /Users/pankaj/output/data.Xml
Unzipping to /Users/pankaj/output/DB.xml
Unzipping to /Users/pankaj/output/item.XML
Unzipping to /Users/pankaj/output/item.xsd
Unzipping to /Users/pankaj/output/ms/data.txt
Unzipping to /Users/pankaj/output/ms/project.doc

That’s all about java unzip file example.


Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

Sign up
About the authors
Default avatar
Pankaj

author

Developer and author at DigitalOcean.

Still looking for an answer?

Was this helpful?

This is the code I’m using which is working fine with sub directories. No external libraries used. package main.java; import java.io.BufferedInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; public class UnzipFile { public static void main(String[] args) throws IOException { String fileZip = “src/main/resources/abcd/abc.zip”; File destDir = new File(“src/main/resources/abcd”); try (ZipFile file = new ZipFile(fileZip)) { Enumeration zipEntries = file.entries(); while (zipEntries.hasMoreElements()) { ZipEntry zipEntry = zipEntries.nextElement(); if (zipEntry.isDirectory()) { String subDir = destDir + “\\” + zipEntry.getName(); File as = new File(subDir); as.mkdirs(); } else { // Create new json file File newFile = new File(destDir, zipEntry.getName()); String extractedDirectoryPath = destDir.getCanonicalPath(); String extractedFilePath = newFile.getCanonicalPath(); if (!extractedFilePath.startsWith(extractedDirectoryPath + File.separator)) { throw new IOException("Entry is outside of the target dir: " + zipEntry.getName()); } BufferedInputStream inputStream = new BufferedInputStream(file.getInputStream(zipEntry)); try (FileOutputStream outputStream = new FileOutputStream(newFile)) { while (inputStream.available() > 0) { outputStream.write(inputStream.read()); } } } } } } }

- Chamlini

    This code is insecure and vulnerable to the Zip Slip vulnerability. https://snyk.io/research/zip-slip-vulnerability

    - Florent Guillaume

      This code as-is does not work with sub directories.

      - Manoj Kidambi

        Hiii, Can we unzip .7z format? i am not getting any reasult for unzip .7z file format

        - Painter Priyank

          Hi Pankaj, The code is working well if zip not contains any file in it if the zip contains any file then its throws file not found exception. Thanks Ajaya

          - Ajaya

            The code will fail when a ZipEntry is only a directory. You must make a check of it. if(ze.isDirectory()){…}

            - Yeung

              How to unzip folder having file names with special characters for e.g. test.zip having file with name fndStaticLookups_finder=LookupTypeFinder%3BBindLookupType%3DACTIVITY_SHOWTIMEAS_CD.json

              - Ashok

                can any one give me 100% generated test case of junit of above code

                - Nirdesh Kumar

                  This code is not working

                  - anshu

                    This does not handle zip folders that contain sub directories. You need to differentiate between a file and directory in the code

                    - rw