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
author image

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities. Read all published posts by

Comments

avatar
48 Comment threads
19 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
55 Comment authors
NiranjanFlorent GuillaumeJi?í HorákAshokDavid Gong Recent comment authors
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.

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

Estuardo Lopez
Guest
Estuardo Lopez

in unZipIt method is outputFolder instead OUTPUT_FOLDER, yes.

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

trackback
How to compress files in ZIP format | J2EE Web Development Tutorials

[…] How to decompress it from a Zip file […]

trackback
Java I/O Tutorials | J2EE Web Development Tutorials

[…] Decompress files from a ZIP file […]

Slava Semushin
Guest
Slava Semushin

Thank you for you example!

I’ve tried it and it doesn’t work for me when ZIP archive contains directories. I resolved it by calling ZipEntry.isDirectory() and skip data copying if it is a directory.

Snorkelman
Guest
Snorkelman

For keys when both kind – directories and files are in zip – here is the complete class: package 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:\\jquery.progressbar.1.1.zip"; private static final String OUTPUT_FOLDER = "C:\\jqueryprogressbar11zip"; 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… Read more »

Krishna
Guest
Krishna

The code is helpful , but for some reason the line
new File(newFile.getParent()).mkdirs();
is not getting executed … hence I modified my code to below ..

byte[] buffer = new byte[1024];
try {
ZipInputStream zis = new ZipInputStream(new FileInputStream(
essClientZip));
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
String fileName = ze.getName();
File newFile = new File(essBVTTempArea + File.separator
+ fileName);
System.out.println(“file unzip : ”
+ newFile.getAbsoluteFile());
if (ze.isDirectory())
{
String temp = newFile.getCanonicalPath();
new File(temp).mkdir();
}
else{
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(“Unzip of ESS client is completed”);

} catch (IOException ex) {
ex.printStackTrace();
}

Yahya Alshha
Guest
Yahya Alshha

Thank’s For Your Modification It’s Help Me 🙂

Vanya
Guest
Vanya

Thanks so much. At first I didn’t check whether the zipentry is directory either and that caused a lot of error.

Manojkumar
Guest
Manojkumar

Hi every one,

I am having one password protected file, which is created using
PKZIP utility (http://www.pkware.com/software/pkzip)

My question how do i encrypt zip file if i don’t know which encryption Algorithm,
it’s using. I have the password.

let me know if any one is having any idea.

changoleon
Guest
changoleon

Thanks a lot! It was very useful! Greetings!

Aleksandar Fotev
Guest
Aleksandar Fotev

Not sure if this is the right place to post this but maybe it will help somebody. Mine problem was that i had a zip inside of my runnable jar file that needed to be extracted . The zip had folders inside. how to get the zip file from inside the jar: InputStream stream; stream = this.getClass().getClassLoader().getSystemResourceAsStream("resources/Sounds.zip"); where the resources is the folder/package inside of the root of the jar now is the rest of the code (a little modification of the original one) package system; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.zip.ZipEntry;… Read more »

Felix
Guest
Felix

Thanks a lot! I was happy that someone posted a solution to the same problem as I had. There should be more people like you. 🙂

m13g7
Guest
m13g7

getResouceAsStream() is returning null, even though the zip file is present. Any idea why this happens?

Chitra
Guest
Chitra

I m also gettin the same error
getResourceAsStream() is returning null…
If got the solution please reply

Sambhav
Guest
Sambhav

Same can be achieved out of the box using Ant Compress library

http://ant.apache.org/antlibs/compress/

Maven dependency:-

<dependency>
	<groupId>org.apache.ant</groupId>
	<artifactId>ant-compress</artifactId>
	<version>1.2</version>
</dependency>
Unzip unzipper = new Unzip();
unzipper.setSrc(theZIPFile);
unzipper.setDest(theTargetFolder);
unzipper.execute();
Rajni
Guest
Rajni

Hi,

Please can you guide me, how can i convert packed field to unpack field. packed field is coming from mainframe.

thanks in advance.

Rohit
Guest
Rohit

I tried this code , It works perfectly with .zip files only. but not with .rar. It returns null. If I want extract data from .rar file so what to do?

ClintJCL
Guest
ClintJCL

Rar and Zip are two different things./ Why would you possibly think code for one would work for the other?

Nayyereh Fazileh
Guest
Nayyereh Fazileh

Hi, Do you know how can I decompress a .rar file?

Dhinakaran
Guest
Dhinakaran

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

File folder = new File(OUTPUT_FOLDER);

Chinthaka D
Guest
Chinthaka D

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

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! 🙂

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

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

Chen Jiling
Guest
Chen Jiling

The IO will not get closed if any exceptions.

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

arpitsharma200
Guest
arpitsharma200

thanks

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

yair
Guest
yair

as always, everything works in mkyong.com

Vishal Dasa
Guest
Vishal Dasa

Thanks man, you are really awesome

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.

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

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?

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??

Paul Muntyanu
Guest
Paul Muntyanu

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