O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required