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):
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
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.