Tech and Media Labs
This site uses cookies to improve the user experience.




Java ZipFile Tutorial

Jakob Jenkov
Last update: 2016-12-20

The Java ZipFile class (java.util.zip.ZipFile) can be used to read files from a ZIP file. The ZipFile class is actually quite easy to use. This tutorial will show you how to use the ZipFile class.

Creating a ZipFile Instance

In order to use the Java ZipFile class you must first create a ZipFile instance. Here is an example of creating a Java ZipFile instance:

 ZipFile zipFile = new ZipFile("d:\\data\\myzipfile.zip");

As you can see, the ZipFile class takes a single parameter in its constructor. This parameter is the path to the ZIP file to open.

Getting a ZipEntry

Each file in the ZIP file is represented by a ZipEntry (java.util.zip.ZipEntry). To extract a file from the ZIP file you can call the method getEntry() method on the ZipFile class. Here is an example of calling getEntry():

ZipEntry zipEntry = zipFile.getEntry("file1.txt");

This example gets a ZipEntry representing the file file1.txt which is contained in the ZIP file.

If the file you want to extract is located in one or more directories inside the ZIP file, include the directories in the path, like this:

ZipEntry zipEntry = zipFile.getEntry("dir/subdir/file1.txt");

Reading the File

To read the file represented by a ZipEntry you can obtain an InputStream from the ZipFile like this:

ZipEntry zipEntry = zipFile.getEntry("dir/subdir/file1.txt");

InputStream inputStream = this.zipFile.getInputStream(zipEntry);

The InputStream obtained from the getInputStream() of the ZipFile class can be read like any other Java InputStream.

Listing All Entries in a ZipFile

You can list all entries contained in a ZipFile using the entries() method. Here is an example of calling the ZipFile entries() :

Enumeration<? extends ZipEntry> entries = zipFile.entries();

You can iterate the Enumeration returned by the entries() method like this:

Enumeration<? extends ZipEntry> entries = zipFile.entries();

while(entries.hasMoreElements()){
    ZipEntry entry = entries.nextElement();
    if(entry.isDirectory()){
        System.out.println("dir  : " + entry.getName());
    } else {
        System.out.println("file : " + entry.getName());
    }
}

Jakob Jenkov




Copyright  Jenkov Aps
Close TOC