Java Reference
In-Depth Information
Now, you can read the data from the ZipInputStream object for the current zip entry. You can save the data
for the zip entry in a file or any other storage medium. You can check if the zip entry is a directory by using its
isDirectory() method of the ZipEntry class.
Listing 9-4 illustrates how to read contents of a ZIP file. The example does not check for some of the errors. It does
not check if a file already exists before overwriting it. It also assumes that all entries are files. The program expects
a ziptest.zip file in your current working directory. It extracts all files from the ZIP file and outputs the path of the
directory containing the extracted files. You may get a different output.
Listing 9-4. Reading Contents of a ZIP File
// UnzipUtility.java
package com.jdojo.archives;
import java.util.zip.ZipEntry;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.util.zip.ZipInputStream;
public class UnzipUtility {
public static void main(String[] args) {
String zipFileName = "ziptest.zip";
String unzipdirectory = "extracted";
unzip(zipFileName, unzipdirectory);
}
public static void unzip(String zipFileName, String unzipdir) {
try (ZipInputStream zis = new ZipInputStream(
new BufferedInputStream(
new FileInputStream(zipFileName)))) {
// Read each entry from the ZIP file
ZipEntry entry = null;
while((entry = zis.getNextEntry()) != null) {
// Extract teh entry's contents
extractEntryContent(zis, entry, unzipdir);
}
System.out.println(
"ZIP file's contents have been extracted to " +
(new File(unzipdir)).getAbsolutePath());
}
catch (IOException e) {
e.printStackTrace();
}
}
Search WWH ::




Custom Search