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
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.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

  • Pingback: great post to read()

  • Pingback: right here()

  • Pingback: alkaline water()

  • Pingback: alkaline water()

  • Pingback: visit site()

  • Pingback: pay plan()

  • Pingback: alkaline water brands()

  • Pingback: water ionizer()

  • Pingback: house blue()

  • Pingback: zak?ad szklarski piotrków trybunalski()

  • Pingback: water ionizer loans()

  • Pingback: plumbers hero can()

  • Pingback: old brass plumbers torch()

  • Pingback: auto locksmith santa cruz()

  • Pingback: locksmithing 101 master keying by the numbers()

  • Pingback: like it()

  • Pingback: electrician vs carpenter()

  • Pingback: paypal loans()

  • Pingback: pay per day loan plans()

  • Pingback: Instagram likes kopen()

  • Pingback: laan penge nu sms()

  • Pingback: alkaline water machine()

  • Pingback: laan penge nu 18 aar()

  • Pingback: fue()

  • Pingback: car parking()

  • Pingback: stop parking()

  • Pingback: DIRECTV channels()

  • Pingback: DIRECTV vs Cable()

  • Pingback: Blue Coaster33()

  • 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! :)

  • http://google.com Peter D’mello

    THIS CODE SUX

    • http://www.mkyong.com mkyong

      Why? not working?

  • http://www.sajeewi.com Chinthaka D

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

  • Dhinakaran

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

    File folder = new File(OUTPUT_FOLDER);

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

  • 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.

  • http://www.expunto.com Sambhav

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

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

    Maven dependency:-

    &lt;dependency&gt;
    	&lt;groupId&gt;org.apache.ant&lt;/groupId&gt;
    	&lt;artifactId&gt;ant-compress&lt;/artifactId&gt;
    	&lt;version&gt;1.2&lt;/version&gt;
    &lt;/dependency&gt;
    Unzip unzipper = new Unzip();
    unzipper.setSrc(theZIPFile);
    unzipper.setDest(theTargetFolder);
    unzipper.execute();
  • 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.

  • 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;
    import java.util.zip.ZipInputStream;
     
    public class UnZip
    {
        List&lt;String&gt; fileList;
     
        UnZip(InputStream stream, File dest)
        {
        	unZipIt(stream,dest); // the stream i got from the first part and dest as a file
        }
     
        /**
         * Unzip it
         * @param stream input zip file
         * @param output zip file output folder
         */
        public void unZipIt(InputStream stream, File dest){
     
         byte[] buffer = new byte[1024];
     
         try{
     
        	//create output directory is not exists
        	File folder = dest;
        	if(!folder.exists()){
        		folder.mkdir();
        	}
     
        	//get the zip file content
        	ZipInputStream zis = 
        		new ZipInputStream(stream);
        	//get the zipped file list entry
        	ZipEntry ze = zis.getNextEntry();
     
        	while(ze!=null){
     
        	   String fileName = ze.getName();
               File newFile = new File(dest + File.separator + fileName);
     
               System.out.println(&quot;file unzip : &quot;+ newFile.getAbsoluteFile());
     
                //create all non exists folders
                //else you will hit FileNotFoundException for compressed folder
     
               if(ze.isDirectory()) 
               {
            	   new File(newFile.getParent()).mkdirs();
               }
               else
               {
            	FileOutputStream fos = null;
     
                new File(newFile.getParent()).mkdirs();
     
                fos = new FileOutputStream(newFile);             
     
                int len;
                while ((len = zis.read(buffer)) &gt; 0) 
                {
           		fos.write(buffer, 0, len);
                }
     
                fos.close();   
               }
     
               ze = zis.getNextEntry();
        	}
     
            zis.closeEntry();
        	zis.close();
     
        	System.out.println(&quot;Done&quot;);
     
        }catch(IOException ex){
           ex.printStackTrace(); 
        }
       }    
    }

    with this i was able to extract files and folders from the zip to a desired location.
    Hope it can prevent some headToWall love <3 :)

    • 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. :)

    • http://[email protected] m13g7

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

      • Chitra

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

  • changoleon

    Thanks a lot! It was very useful! Greetings!

  • 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.

  • http://krishnababug,com 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();
    }

    • http://soky.weebly.com Yahya Alshha

      Thank’s For Your Modification It’s Help Me :)

  • 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

      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&lt;String&gt; fileList;
          private static final String INPUT_ZIP_FILE = &quot;C:\\jquery.progressbar.1.1.zip&quot;;
          private static final String OUTPUT_FOLDER = &quot;C:\\jqueryprogressbar11zip&quot;;
       
          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(&quot;file unzip : &quot;+ newFile.getAbsoluteFile());
       
                  //create all non exists folders
                  //else you will hit FileNotFoundException for compressed folder
       
                 if(ze.isDirectory()) 
                 {
              	   new File(newFile.getParent()).mkdirs();
                 }
                 else
                 {
              	FileOutputStream fos = null;
       
                  new File(newFile.getParent()).mkdirs();
       
                  fos = new FileOutputStream(newFile);             
       
                  int len;
                  while ((len = zis.read(buffer)) &gt; 0) 
                  {
             		fos.write(buffer, 0, len);
                  }
       
                  fos.close();   
                 }
       
                 ze = zis.getNextEntry();
          	}
       
              zis.closeEntry();
          	zis.close();
       
          	System.out.println(&quot;Done&quot;);
       
          }catch(IOException ex){
             ex.printStackTrace(); 
          }
         }    
      }
  • Pingback: Java I/O Tutorials | J2EE Web Development Tutorials()

  • Pingback: How to compress files in ZIP format | J2EE Web Development Tutorials()