Java – Unzip

Yesterday we try to zip a folder in Java.
Java – Zip Folder Recursively

So now we need to unzip it. Create the following Java class and try.

package com.wordpress.ykyuen;

import java.io.File;
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 UnZipFile {

  public static void main(String[] args) throws IOException {
    ZipFile zipFile = new ZipFile("C:\\Users\\Administrator\\Desktop\\ykyuen.zip");
    File unzipDir = new File("C:\\Users\\Administrator\\Desktop\\target");
    unzip(zipFile, unzipDir);
  }
  
  public static void unzip(ZipFile zipFile, File unzipDir) {
    Enumeration<? extends ZipEntry> files = zipFile.entries();
    File f = null;
    FileOutputStream fos = null;
    
    while (files.hasMoreElements()) {
      try {
        ZipEntry entry = (ZipEntry) files.nextElement();
        InputStream eis = zipFile.getInputStream(entry);
        byte[] buffer = new byte[1024];
        int bytesRead = 0;
  
        f = new File(unzipDir.getAbsolutePath() + File.separator + entry.getName());
        
        if (entry.isDirectory()) {
          f.mkdirs();
          continue;
        } else {
          f.getParentFile().mkdirs();
          f.createNewFile();
        }
        
        fos = new FileOutputStream(f);
  
        while ((bytesRead = eis.read(buffer)) != -1) {
          fos.write(buffer, 0, bytesRead);
        }
      } catch (IOException e) {
        e.printStackTrace();
        continue;
      } finally {
        if (fos != null) {
          try {
            fos.close();
          } catch (IOException e) {
            // ignore
          }
        }
      }
    }
  }
}

 

Done =)

Reference: Java2s – unzip File Into Directory

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.