Unzip a ZIP File using Java Code

 



Unzip a ZIP File using Java Code


In this tutorial we will see about unzipping a Zip file using Java code. Below example will gives you the code to unzip a zip file by taking zip file and output folder path as input parameters. 



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

public class UnZip {

 public static final void main(String[] args) {

  // Zip file path
  String zipFile = "D:\\myZipFile.zip";

  // Output folder to save the unzip files
  String outputFolder = "D:\\unzipfolder\\";
  
  unzipFile(zipFile, outputFolder);

 }
 
 public static void unzipFile(String zipFile, String outputFolder){
  
  ZipFile zFile = null;

  try {
   zFile = new ZipFile(zipFile);
   Enumeration zEntries = zFile.entries();

   while (zEntries.hasMoreElements()) {
    ZipEntry zipEntry = (ZipEntry) zEntries.nextElement();

    // Check for Directory or not
    if (zipEntry.isDirectory()) {
     // Creating directory
     (new File(zipEntry.getName())).mkdir();
     continue;
    }

    // Unzipping files
    createUnzipFile(zFile.getInputStream(zipEntry),
      new BufferedOutputStream(new FileOutputStream(
        outputFolder + zipEntry.getName())));
   }
   zFile.close();
  } catch (IOException e) {
   e.printStackTrace();
  
  } 
 }

 public static final void createUnzipFile(InputStream iStream,
   OutputStream oStream) {
  try {
   byte[] buffer = new byte[1024];
   int len;
   while ((len = iStream.read(buffer)) >= 0)
    oStream.write(buffer, 0, len);

  iStream.close();
  oStream.close();
  } catch (Exception e) {
   e.printStackTrace();
 
  } 
 }
}






No comments:
Write comments