Unzipping a zip file

This post explains how to unzip a zip file.


package ZipDemo;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class ZipDemo3 {
    public static void main(String[] args) throws FileNotFoundException, IOException {
        String destination = "E:\\Projects\\JavaProjects\\JavaConcepts\\WorkFolder\\Folder1";
        try (ZipFile zipFile = new ZipFile("E:\\Projects\\JavaProjects\\JavaConcepts\\WorkFolder\\Folder1.zip")){
            File folder = new File(destination);
            folder.mkdir();
            Enumeration entries = zipFile.entries();
            for (Enumeration<? extends ZipEntry> e = entries; e.hasMoreElements();) {
                ZipEntry zipEntry = e.nextElement();
                System.out.println(zipEntry.getName());
                if(zipEntry.isDirectory()) {
                    File childFolder = new File(folder, zipEntry.getName());
                    childFolder.mkdir();
                } else {
                    try(FileOutputStream fos = new FileOutputStream(folder.getAbsolutePath() + "\\" + zipEntry.getName())) {
                        InputStream zis = zipFile.getInputStream(zipEntry);
                        byte[] data = new byte[1024];

                        int bytesRead = zis.read(data);
                        while(bytesRead != -1) {
                            fos.write(data,0,bytesRead);
                            bytesRead = zis.read(data);
                        }
                        fos.flush();
                        fos.close();
                    }
                }
            }
        }
    }
}

Explanation

An instance of ZipFile represents the zip file to be unzip. An instance of ZipEntry represents each entry (which can be a folder or file) in the zip file which has to be extracted. We can check whether an entry represents a directory or not using the isDirectory method in ZipEntry class. In the above code if block creates a directory in the destination folder and else block extracts the file.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s