How to decompress files from a ZIP file

In previous article, we show you how to compress files to a zip file format. In this article we will show you how to unzip it.

  1. Read ZIP file with “ZipInputStream
  2. Get the files to “ZipEntry” and output it to “FileOutputStream

1. Decompress ZIP file example

In this example, it will read a ZIP file from “C:\\MyFile.zip“, and decompress all zipped files to “C:\\outputzip” folder.


package com.mkyong.zip;

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

public class UnZip
{
    List<String> fileList;
    private static final String INPUT_ZIP_FILE = "C:\\MyFile.zip";
    private static final String OUTPUT_FOLDER = "C:\\outputzip";
		
    public static void main( String[] args )
    {
    	UnZip unZip = new UnZip();
    	unZip.unZipIt(INPUT_ZIP_FILE,OUTPUT_FOLDER);
    }
    
    /**
     * Unzip it
     * @param zipFile input zip file
     * @param output zip file output folder
     */
    public void unZipIt(String zipFile, String outputFolder){

     byte[] buffer = new byte[1024];
    	
     try{
    		
    	//create output directory is not exists
    	File folder = new File(OUTPUT_FOLDER);
    	if(!folder.exists()){
    		folder.mkdir();
    	}
    		
    	//get the zip file content
    	ZipInputStream zis = 
    		new ZipInputStream(new FileInputStream(zipFile));
    	//get the zipped file list entry
    	ZipEntry ze = zis.getNextEntry();
    		
    	while(ze!=null){
    			
    	   String fileName = ze.getName();
           File newFile = new File(outputFolder + File.separator + fileName);
                
           System.out.println("file unzip : "+ newFile.getAbsoluteFile());
                
            //create all non exists folders
            //else you will hit FileNotFoundException for compressed folder
            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();   
            ze = zis.getNextEntry();
    	}
    	
        zis.closeEntry();
    	zis.close();
    		
    	System.out.println("Done");
    		
    }catch(IOException ex){
       ex.printStackTrace(); 
    }
   }    
}

Output


file unzip : C:\outputzip\pdf\Java-Interview.pdf
file unzip : C:\outputzip\spy\log\spy.log
file unzip : C:\outputzip\utf-encoded.txt
file unzip : C:\outputzip\utf.txt
Done

Reference

  1. Compressing and Decompressing Data Using Java APIs

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Ashwin
Guest
Ashwin

Your site is simply wonderful. Small snippets so useful to use/understand as part of a bigger code. Appreciate it and do let me know if there is anyway I can contribute it to the site in anyway.

Estuardo Lopez
Guest
Estuardo Lopez

in unZipIt method is outputFolder instead OUTPUT_FOLDER, yes.

Nik
Guest
Nik
You must check ZipEntry is directory ir not. If it is directory you must create this else copy it. For example: if (ze.isDirectory()) newFile.mkdirs(); else { FileOutputStream fos = new FileOutputStream(newFile); while ((readed = zis.read(data)) != -1) fos.write(data, 0, readed); }
Gabriel Basilio Brito
Guest
Gabriel Basilio Brito

Exactly

Siddharth Rawat
Guest
Siddharth Rawat

Yes, This would make things work smoothly.

Purinsu
Guest
Purinsu

Just add this code below while(ze!=null){

if (ze.isDirectory()) {

ze = zis.getNextEntry();

continue;

}


rest of the code.
}

maybe I helped a little bit.

Jasmine
Guest
Jasmine

sorry can you post the full code? please

Thanks
Guest
Thanks

FileOutputStream fos = new FileOutputStream(newFile);

int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}

fos.close();

Wouldn’t a BufferedWriter probably be faster ? Just a thought. Thanks for the tuto.

Joseph Francis
Guest
Joseph Francis

Thank you – very nice. This saved me tons of time (posted a small fix) below.

Joseph Francis
Guest
Joseph Francis
//— Here is a fix so that is creates when there are sub-directories .. this creates if needed // Note: If you had run it before, remove the existing files because there may be a blank file holding the spot of the directory import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.apache.commons.io.FilenameUtils; public class FileUnzipper { List fileList; /* * private static final String INPUT_ZIP_FILE = “C:\MyFile.zip”; private * static final String OUTPUT_FOLDER = “C:\outputzip”; * * public static void main( String[] args ) { FileUnzipper unZip = new * FileUnzipper(); unZip.unZipIt(INPUT_ZIP_FILE,OUTPUT_FOLDER); }… Read more »
Rhuan
Guest
Rhuan

Nice, but what about a zip inside a zip?
I’ll need to call the method twice? ‘-‘

Safoora
Guest
Safoora

Very good tutorial. thanks a lot

Safoora
Guest
Safoora

Very nice tutorial..

Andrew Sheron
Guest
Andrew Sheron

Anyway to randomly decompress a zip file?

Jasmine
Guest
Jasmine

sorry, why it download only one file folder? there are more inside my file zip….

Jasmine
Guest
Jasmine

Caused by: android.system.ErrnoException: open failed: ENOTDIR (Not a directory)

Jasmine
Guest
Jasmine

Sorry, how do I have to Call it from the activity? Unzip.main(); ? Unzip(); ?

Jasmine
Guest
Jasmine

and how can I set to know when unzip is ready?

Goutham Nithyananda
Guest
Goutham Nithyananda

When we try to unzip huge file say 2gb. How will ZipInputStream manage the memory aspects, Please explain?

Paul Muntyanu
Guest
Paul Muntyanu

Hi, you need to change “new File(newFile.getParent()).mkdirs()” to this: new File(newFile.getParentFile()).mkdirs()

Bharath B S
Guest
Bharath B S

Hi,

When i run the code with the ZIP file of mediumsize but when my ZIP file is in the size of GB’s the code fails with File Not Found Exception.

Can anyone help me to resolve my issue??

vin
Guest
vin

java.util.zip.ZipException: invalid entry compressed size (expected 4294967295 but got 14454437 bytes)

I am getting this error.How do i solve it?

Ph?m Nguy?n Hà Trung
Guest
Ph?m Nguy?n Hà Trung

Somehow I can’t make your code to work.
– If a folder in the zip file has a . in its name, it is read as a file and stuck there
– If we have a folder inside a folder, there will be errors in various cases
– Your code only works if there’s only 1 folder containing all the files

David Mendoza
Guest
David Mendoza

Mkyong, your advice has been helpful in learning java. I do have a question, how can I read a zip file that contains other zip files? I need to process all files within a zip file that contains other zip files. I want to process (read) all log files. My issues is that my loop doesn’t know how to deal with an embedded zip file. I’l using java zipfile routines.

Vishal Dasa
Guest
Vishal Dasa

Thanks man, you are really awesome

yair
Guest
yair

as always, everything works in mkyong.com

Nuno Brito
Guest
Nuno Brito

This code was problematic. Used a whole morning to get a working code for zip files with multiple folders inside. Ended up using ZT-Zip as alternative. Easy, two lines of code.

Get the Jar and code sample to extract files their GitHub page: https://github.com/zeroturnaround/zt-zip

Nur
Guest
Nur

Hey man, you are awsome. actually this programm saves my time a lot and i change it a bit so that it can go to a directory and fild all zip files and unzip them. thanks again

arpitsharma200
Guest
arpitsharma200

thanks

Abubakr
Guest
Abubakr

I’m getting the below error
Exception in thread “main” java.lang.IllegalArgumentException: MALFORMED

when I have a complex zip file (zip inside zip or mix files and folders inside zip)

Max
Guest
Max

the reason is the file or folder names in Unicode languages

Chen Jiling
Guest
Chen Jiling

The IO will not get closed if any exceptions.

Vaibhav
Guest
Vaibhav

Hi this is nice tutorial,
what if I want to check if file exists with same size then skip that file unzipping and move ahead while unzipping

SteauaAcumSteauaMereu
Guest
SteauaAcumSteauaMereu

I think zis.closeEntry() call should be inside the while before calling getNextEntry. This way you close every entry not only the last one.

Gabriel Basilio Brito
Guest
Gabriel Basilio Brito

Yep, this is right

Selene
Guest
Selene

Hi,

First of all, thanks a lot for the code above. I noticed something though. It will not extract Directories in the ZIP which contains no file.

I want to really extract all even if it is empty.

I hope someone can help me out.

Thanks! :)

Chinthaka D
Guest
Chinthaka D

Thanks a lot your web simply awesome. thanks for the help

Dhinakaran
Guest
Dhinakaran

Why do you use the Global variable? Why dont you use method parameter ‘outputFolder’?

File folder = new File(OUTPUT_FOLDER);