Java - Read zip file with ZipFile class

Introduction

You can use the ZipFile class to read the contents of a ZIP file or list its entries.

ZipFile allows random access to ZIP entries, whereas ZipInputStream allows sequential access.

The entries() method of a ZipFile object returns an enumeration of all zip entries in the file.

Its getInputStream() method returns the input stream to read the content of a ZipEntry object.

The following code shows how to use the ZipFile class.

Demo

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

public class Main {
  public static void main(String[] args) throws IOException {
    // Create a ZipFile object using the ZIP file name
    ZipFile zf = new ZipFile("ziptest.zip");

    // Get the enumeration for all zip entries and loop through them
    Enumeration<? extends ZipEntry> e = zf.entries();
    ZipEntry entry = null;//from  w ww .j  av  a2 s . co  m

    while (e.hasMoreElements()) {
      entry = e.nextElement();

      // Get the input stream for the current zip entry
      InputStream is = zf.getInputStream(entry);

      /* Read data for the entry using the is object */

      // Print the name of the entry
      System.out.println(entry.getName());
    }
  }
}

Related Topic