Reading and Writing JAR or Zip Archives
Problem
You need to create and/or extract from a JAR archive or a file in the PkZip or WinZip format.
Solution
You could use the jar program in the Java
Development Kit, since its file format is identical with the zip
format with the addition of the META-INF directory to contain
additional structural information. But since this is a book about
programming, you are probably more interested in the
ZipFile and
ZipEntry
classes and the stream classes that they
provide access to.
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.[25] 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);
If you want to see whether a given file is present in the archive,
you can call the getEntry( ) method with a filename. More commonly, you’ll ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access