Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java ZipOutputStream: close each entry and the archive before publication

Last updated: 5 Oct 20265 min read
tutorial
AdvancedBy AITrove Editorial

ZipOutputStream builds entries and writes central-directory metadata when the archive is finished. A successful entry write does not by itself produce a complete ZIP file.

Operational contract

The method creates a new archive with one fixed, application-owned entry name, writes a bounded manifest, closes the entry, and closes the stream. Only then can its caller stage or publish the file. If a write fails, the partial archive path can remain; the owner should remove or quarantine it. Untrusted entry names require separate path and duplicate rules before adding them. ZIP compresses data but does not authenticate or encrypt it merely because an archive exists.

Failure case

A review worker writes receipt-47.manifest into a ZIP for handoff. It must not notify readers after write returns while the central directory is still missing. The stream scope completes first. A failure leaves the destination untrusted and requires cleanup before another attempt reuses that name.

Java code

Java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ReceiptZipWriter {
    public static void create(Path stagingArchive, byte[] manifest) throws IOException {
        if (manifest.length > 47_000) throw new IllegalArgumentException("Manifest exceeds cap");
        try (ZipOutputStream zip = new ZipOutputStream(Files.newOutputStream(stagingArchive,
                java.nio.file.StandardOpenOption.CREATE_NEW,
                java.nio.file.StandardOpenOption.WRITE))) {
            zip.putNextEntry(new ZipEntry("receipt-47.manifest"));
            zip.write(manifest);
            zip.closeEntry();
        }
    }
}

Performance and ownership cost

Writing B bytes costs O(B) compression work with buffering inside the stream. The method retains the caller's bounded byte array rather than another full copy. Archive finalization and later atomic publication add I/O that must complete before readers are told the artifact is ready.

Common Mistakes

  • Do not publish an archive before its stream closes.
  • Do not leave a failed partial archive under a trusted final name.
  • Do not accept unvalidated user-controlled entry names.

Connected lessons

java
archive and compression boundaries
zip-output-finalization
Storage details