Sample Programs

Sample java program to unzip a Zip File

package org.jusfortechies.example; 

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.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class UnZipExample{
    
  public static final void copyInputStream(InputStream in, OutputStream out)
  throws IOException
  {
    byte[] buffer = new byte[1024];
    int len;

    while((len = in.read(buffer)) >= 0)
      out.write(buffer, 0, len);

    in.close();
    out.close();
  }

  public static final void main(String[] args) {
    Enumeration zipEntries;
    ZipFile zipFile;

    try {
      //Zip file to be unzipped  
      zipFile = new ZipFile("TestZip.zip");

      zipEntries = zipFile.entries();

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

        //Check if the entry is a directory
        if(zipEntry.isDirectory()) {
          // Assume directories are stored parents first then children.
          System.err.println("Extracting directory: " + zipEntry.getName());
          // This is just for demonstration purposes.
          (new File(zipEntry.getName())).mkdir();
          continue;
        }

        System.err.println("Extracting file: " + zipEntry.getName());
        
        copyInputStream(zipFile.getInputStream(zipEntry),
           new BufferedOutputStream(new FileOutputStream(zipEntry.getName())));
      }

      zipFile.close();
    } catch (IOException ioe) {
      System.err.println("Unhandled exception:");
      ioe.printStackTrace();
      return;
    }
  }

} 

 

You dont need additional jars to run the above example



blog comments powered by Disqus