How to list the contents of a zip file in Java

Problem statement

Given a zip file, list the filenames of the compressed files.

Suppose four different files are compressed as a zip file. We need to list their names.

Solution

Every file in the zip file is represented as ZipEntry in Java. There are two ways to read the zip files.

  1. Use streams in Java.

  2. Use the entries() method.

Code

Using streams

In this method, we use the stream() method on the ZipFile object that returns the streams of the ZipEntry objects.

Consider the following code example.

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.List;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class Main {
private static void listContents(String fileName){
ZipFile zipFile = null;
File file = new File(fileName);
try {
zipFile = new ZipFile(file);
List<String> fileContent = zipFile.stream().map(ZipEntry::getName).collect(Collectors.toList());
System.out.println("ZipFile contents - " + fileContent);
zipFile.close();
}
catch (IOException ioException) {
System.out.println("Error opening zip file" + ioException);
}
}
public static void main(String[] args) {
String fileName = "file.zip";
listContents(fileName);
}
}

Explanation

Step 1: The zip file’s name is used to create a File object.

Step 2: The File object created in Step 1 is passed to create a ZipFile object.

Step 3: We get the list of the contents in the zip file in ZipEntry objects by using the .stream() method on the ZipFile object.

Step 4: All the file names are collected and stored as a ‘List’ using the map() function on stream().

The entries() method

The entries() method on the ZipFile object returns an enumeration, which we can loop through the elements of the zip file.

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class Zip {
private static void listContents(String fileName){
ZipFile zipFile = null;
File file = new File(fileName);
try {
zipFile = new ZipFile(file);
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
String entryName = entry.getName();
System.out.println("ZIP Entry: " + entryName);
}
zipFile.close();
}
catch (IOException ioException) {
System.out.println("Error opening zip file" + ioException);
}
}
public static void main(String[] args) {
listContents("file.zip");
}
}

Free Resources