Reading and Writing JAR or Zip Archives


You need to create and/or extract from a JAR archive or a file in the PkZip or WinZip format.


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.


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

Get Java Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.