How to read contents of a ZIP file in Java
- Details
- Written by Nam Ha Minh
- Last Updated on 27 July 2019   |   Print Email
ZipFile zipFile = new ZipFile(zipFilePath); Enumeration<? extends ZipEntry> entries = zipFile.entries();Each entry is of type ZipEntry which provides the following methods for reading information of an individual entry (to name a few):
- getName(): returns the name of the entry in form of a relative path
- getComment(): returns comment of the entry
- getCompressedSize(): returns the compressed size of the entry in bytes.
- getSize(): returns the normal size (uncompressed) of the entry in bytes.
- isDirectory(): tells whether the entry is a directory or not.
import java.io.*;
import java.util.*;
import java.util.zip.*;
/**
* This program reads contents of a ZIP file.
*
* @author www.codejava.net
*/
public class ReadZipFile {
private static void read(String zipFilePath) {
try {
ZipFile zipFile = new ZipFile(zipFilePath);
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
String name = entry.getName();
long compressedSize = entry.getCompressedSize();
long normalSize = entry.getSize();
String type = entry.isDirectory() ? "DIR" : "FILE";
System.out.println(name);
System.out.format("\t %s - %d - %d\n", type, compressedSize, normalSize);
}
zipFile.close();
} catch (IOException ex) {
System.err.println(ex);
}
}
public static void main(String[] args) {
String zipFilePath = args[0];
read(zipFilePath);
}
} Run this program like this:java ReadZipFile <zip_file_path>
For example:java ReadZipFile exercises_week12.zip
This would print the following output:exercise1/
DIR - 0 - 0
exercise1/Book.class
FILE - 868 - 1906
exercise1/Book.java
FILE - 442 - 1689
exercise1/Book.java~
FILE - 258 - 1066
exercise1/Main.class
FILE - 1631 - 3159
exercise1/Main.java
FILE - 707 - 1964
exercise2/
DIR - 0 - 0
exercise2/Book.class
FILE - 868 - 1906
exercise2/Book.java
FILE - 442 - 1689
exercise2/BookStats.class
FILE - 2558 - 5748
exercise2/BookStats.java
FILE - 897 - 3292
API References:
Related Java Zip File Tutorials:
- How to compress files in ZIP format in Java
- How to extract a ZIP file in Java
- How to compress directories to ZIP file in Java
Other Java File IO Tutorials:
- How to Read and Write Text File in Java
- How to Read and Write Binary Files in Java
- Java IO - Common File and Directory Operations Examples
- Java Serialization Basic Example
- Understanding Java Externalization with Examples
- How to execute Operating System Commands in Java
- 3 ways for reading user's input from console in Java
- File change notification example with Watch Service API
- Java Scanner Tutorial and Code Examples
About the Author:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
Comments