Java Reference
In-Depth Information
public static void extractEntryContent(ZipInputStream zis,
ZipEntry entry,
String unzipdir)
throws IOException, FileNotFoundException {
String entryFileName = entry.getName();
String entryPath = unzipdir + File.separator + entryFileName;
// Create the entry file by creating necessary directories
createFile(entryPath);
// Create an output stream to extract the content of the
// zip entry and write to the new file
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(entryPath));
byte[] buffer = new byte[1024];
int count = -1;
while((count = zis.read(buffer)) != -1) {
bos.write(buffer, 0, count);
}
bos.close();
}
public static void createFile(String filePath) throws IOException {
File file = new File(filePath);
File parent = file.getParentFile();
// Create all parent directories if they do not exist
if (!parent.exists()) {
parent.mkdirs();
}
file.createNewFile();
}
}
ZIP file's contents have been extracted to C:\books\javabook\extracted
It is easier to use the ZipFile class to read the contents of a ZIP file or list its entries. For example, ZipFile allows
random access to ZIP entries, whereas ZipInputStream allows sequential access. The entries() method of a ZipFile
object returns an enumeration of all zip entries in the file. Its getInputStream() method returns the input stream
to read the content of a ZipEntry object. The following snippet of code shows how to use the ZipFile class. You
can rewrite the code in Listing 9-4 using the ZipFile class instead of the ZipOutputStream class as an exercise. The
ZipFile class comes in handy when you just want to list the entries in a ZIP file.
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
...
 
Search WWH ::




Custom Search