Chapter 14. Zip and Jar files

Table of Contents

Building Zip files
Building Jar files
Reading from Zip and Jar files

The ZipFileSystemBuilder and JarFileSystemBuilder classes can be used to build read only FileSystem:s on Zip and Jar files. There are also support classes for building new Zip and Jar files.

A ZipCreator object can be used to create a new Zip file. It builds the file using ZipEntryInfo objects that are returned from an Iterator. A ZipEntryInfo object contains information that the ZipCreator uses for creating a ZipEntry for a file or a directory in the Zip file.

Note

EntityFS ZipCreator uses Java's ZipOutputStream to create Zip files. It is somewhat limited in how the created file can be configured. The At4J project has a Zip builder that can create more types of Zip files.

The EntityIteratorToZipEntryInfoIteratorAdapter can be used to adapt any kind of EntityView iterator to a ZipEntryInfo Iterator.

Below is a simple example of how a Zip file can be created.

Example 14.1. Building a Zip file

// Build a Zip file containing all files and directories under the directory d1.
// Put the new file zip.zip in the directory d2.
new ZipCreator(
  new EntityIteratorToZipEntryInfoIteratorAdapter(d1, 
    Directories.getDepthLastIterator(d1)),
  d2, "zip.zip").create();

// The ZipCreator will acquire read locks on the files and directories
// added to the Zip file when it needs them.

The next example is a slightly more advanced example that builds a Zip file from files in two different directory hierarchies.


A Jar file can be built just like a Zip file. The JarCreator works just like the ZipCreator, with the added setManifest method for setting a Manifest.

Example 14.3. Building a Jar file

// Build a Jar file containing all files and directories under the directory d1.
// Use a custom manifest. Put the new file jar.jar in the directory d2.
new JarCreator(
  new EntityIteratorToJarEntryInfoIteratorAdapter(d1, 
    Directories.getDepthLastIterator(d1)),
  d2, "jar.jar").
  setManifest(
    new Manifest(
      new ByteArrayInputStream(
        // Note the trailing \n after the last row...
        "Manifest-Version: 1.0\nCreated-By: 1.0 me\n".getBytes()))).create();

To read the contents from a Zip or Jar file, create a Zip or Jar file system on the file and read entities from the file system.

Example 14.4. Reading entities from a Zip file

// Read the file d1/text2.txt from the Zip file texts.zip in the directory d
FileSystem fs = new ZipFileSystemBuilder().
  setZipFile(Directories.getFile(d, "texts.zip")).
  create();
try
{
  info("Contents of text2.txt: " +
    Files.readTextFile(
      Directories.getFile(
        fs.getRootDirectory(),
        new RelativeLocation("d1/text2.txt"))));
}
finally
{
  // Don't forget to close the Zip file system when you're done with it.
  fs.close();
}
  

If you want to just unzip a Zip or Jar archive, use any of ZipFiles's unzip methods.