Package java.util.zip

Class ZipOutputStream

  • All Implemented Interfaces:
    Closeable, Flushable, AutoCloseable
    Direct Known Subclasses:
    JarOutputStream

    public class ZipOutputStream
    extends DeflaterOutputStream
    Used to write (compress) data into zip files.

    ZipOutputStream is used to write ZipEntrys to the underlying stream. Output from ZipOutputStream can be read using ZipFile or ZipInputStream.

    While DeflaterOutputStream can write compressed zip file entries, this extension can write uncompressed entries as well. Use ZipEntry.setMethod(int) or setMethod(int) with the ZipEntry.STORED flag.

    Example

    Using ZipOutputStream is a little more complicated than GZIPOutputStream because zip files are containers that can contain multiple files. This code creates a zip file containing several files, similar to the zip(1) utility.

     OutputStream os = ...
     ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(os));
     try {
         for (int i = 0; i < fileCount; ++i) {
             String filename = ...
             byte[] bytes = ...
             ZipEntry entry = new ZipEntry(filename);
             zos.putNextEntry(entry);
             zos.write(bytes);
             zos.closeEntry();
         }
     } finally {
         zos.close();
     }