Java Reference
In-Depth Information
terested in the ZipFile and ZipEntry classes and the stream classes to which they provide
access.
Discussion
The class java.util.zip.ZipFile is not an I/O class per se , but a utility class that allows
you to read or write the contents of a JAR or ZIP-format file. [ 37 ] When constructed, it creates
a series of ZipEntry objects, one to represent each entry in the archive. In other words, the
ZipFile represents the entire archive, and the ZipEntry represents one entry, or one file that
has been stored (and compressed) in the archive. The ZipEntry has methods like
getName() , which returns the name that the file had before it was put into the archive, and
getInputStream() , which gives you an InputStream that will transparently uncompress
the archive entry by filtering it as you read it. To create a ZipFile object, you need either the
name of the archive file or a File object representing it:
ZipFile zippy = new ZipFile(fileName);
To see whether a given file is present in the archive, you can call the getEntry() method
with a filename. More commonly, you'll want to process all the entries; for this, use the
ZipFile object to get a list of the entries in the archive, in the form of an Enumeration (see
Using Iterators or Enumerations for Data-Independent Access ) :
Enumeration all = zippy.entries( );
while (all.hasMoreElements( )) {
ZipEntry entry = (ZipEntry)all.nextElement( );
...
}
We can then process each entry as we wish. A simple listing program could be:
if (entry.isDirectory( ))
println("Directory: " + e.getName( ));
else
println("File: " + e.getName( ));
A fancier version would extract the files. The program in Example 10-12 does both: it lists
by default, but with the -x (extract) switch, it actually extracts the files from the archive.
 
Search WWH ::




Custom Search