Unzipping Files with java.util.zip.ZipFile

he Java core packages include jave.util.zip, which is useful forcreating and reading compressed files or archives in the ZIP and GZIPformats. ZIP files form the basis for the JAR file format, so it wasnatural to include classes for manipulating ZIP files as part of thestandard Java APIs. This functionality is enormously useful, becauseit saves you the time of creating custom file archive formats for yourapplications. You can use the ZipFile class to read entries ina ZIP file. The entries are represented by instances of the ZipEntryclass, which contains information such as the size, name, compressionmethod, and timestamp of the entry. ZipFile.entries() will return theentries as an Enumeration which you can step through to access all ofthe entries. Once you have found an entry of interest,ZipFile.getInputStream(ZipEntry) will produce an InputStream, fromwhich the archived entry can be read.

The following program demonstrates how to use the ZipFile class tocreate a simple unzip utility. It simply cycles through all of theentries in the file and copies each entry to a new file by reading itsinput stream. If an entry is a directory, it is created. The exampleis not robust and is only intended to demonstrate the ZipFile class.Obvious additions would include checking if a file already exists beforecreating it, prompting the user if it should be overwritten, as wellas other error checking. View the example>:

import java.io.*;import java.util.*;import java.util.zip.*;public class Unzip {  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 entries;    ZipFile zipFile;    if(args.length != 1) {      System.err.println("Usage: Unzip zipfile");      return;    }    try {      zipFile = new ZipFile(args[0]);      entries = zipFile.entries();      while(entries.hasMoreElements()) {        ZipEntry entry = (ZipEntry)entries.nextElement();        if(entry.isDirectory()) {          // Assume directories are stored parents first then children.          System.err.println("Extracting directory: " + entry.getName());          // This is not robust, just for demonstration purposes.          (new File(entry.getName())).mkdir();          continue;        }        System.err.println("Extracting file: " + entry.getName());        copyInputStream(zipFile.getInputStream(entry),           new BufferedOutputStream(new FileOutputStream(entry.getName())));      }      zipFile.close();    } catch (IOException ioe) {      System.err.println("Unhandled exception:");      ioe.printStackTrace();      return;    }  }}
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: