GZIPOutputStream writes a compressed stream whose trailer is completed when the stream finishes or closes. Reading the destination before that point risks an incomplete artifact.
Java GZIPOutputStream: close before using the compressed bytes
Operational contract
The method bounds its source payload, writes it through a GZIPOutputStream, and returns the ByteArrayOutputStream contents only after the compressor closes. The compressor owns the sink for the scoped call. For a file destination, write to a staging name and publish only after close and any durability decision. Compression is not encryption; it does not protect private manifest data. This in-memory version is suitable only for bounded payloads and does not claim a useful compression ratio for every input.
Failure case
A batch contains 47,000 bytes of receipt text. Returning the output array while the compressor is still open could omit the final trailer. The try-with-resources scope ends first; the caller receives a complete GZIP member or an exception.
Java code
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
public class ManifestGzipWriter {
public static byte[] compress(byte[] manifest) throws IOException {
if (manifest.length > 47_000) throw new IllegalArgumentException("Manifest exceeds cap");
ByteArrayOutputStream destination = new ByteArrayOutputStream();
try (GZIPOutputStream compressed = new GZIPOutputStream(destination)) {
compressed.write(manifest);
}
return destination.toByteArray();
}
}Performance and ownership cost
Compression scans B input bytes and retains O(B) output in this bounded design, though exact compressed size depends on data. The final toByteArray copies the compressed bytes. Repeated large batches should stream to a staged file under a byte and time budget.
Common Mistakes
- Do not read compressed output before finish or close.
- Do not call compression encryption.
- Do not publish a staged file before the compressor closes successfully.
Connected lessons
- Java GZIPInputStream: cap bytes after decompression
- Java Files.move: atomic publication is a filesystem contract
- Java file I/O: UTF-8, streaming reads, and path ownership
- Java ZipFile entries: reject duplicate names before selection
- Java ZIP CRC32: detect corruption without claiming authenticity
- Java ZipOutputStream: close each entry and the archive before publication
- Java XML and archive boundaries quiz
- Advanced Java
