Tutorial

Java Unzip File Example

Published on August 3, 2022
author

Pankaj

Java Unzip File Example

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.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

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.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
June 17, 2020

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

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    October 29, 2019

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

    - Florent Guillaume

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      September 12, 2019

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

      - Manoj Kidambi

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        February 25, 2019

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

        - Painter Priyank

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          December 26, 2018

          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

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            December 12, 2018

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

            - Yeung

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              November 20, 2018

              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

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                May 11, 2018

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

                - Nirdesh Kumar

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  February 10, 2018

                  This code is not working

                  - anshu

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    November 28, 2017

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

                    - rw

                      Try DigitalOcean for free

                      Click below to sign up and get $200 of credit to try our products over 60 days!

                      Sign up

                      Join the Tech Talk
                      Success! Thank you! Please check your email for further details.

                      Please complete your information!

                      Featured on Community

                      Get our biweekly newsletter

                      Sign up for Infrastructure as a Newsletter.

                      Hollie's Hub for Good

                      Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

                      Become a contributor

                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                      Welcome to the developer cloud

                      DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

                      Learn more