Round-trip a compressed report in Java

Close the GZIP output stream to write its trailer before reading the compressed bytes. The round trip also works for an empty report.

A simple example

Compress, finish, then decompress

  1. Start with Text A
  2. Do this Compress, finish, then decompress
  3. Result A
Finishing the compressed stream writes the information the reader needs.

Apply it to a real problem

  1. Start with Report row=2 and an empty report
  2. Do this Round-trip both through GZIP
  3. Result row=2 and empty text
The report's contents survive even when its length is zero.
Advertisements

Run the example

Save as Main.java and run java Main.java with JDK 21.

Main.java
import java.io.*;
import java.util.zip.*;
import java.nio.charset.StandardCharsets;

public class Main {
    public static void main(String[] args) throws Exception {
        for (String text : new String[]{"row=2", ""}) {
            var bytes = new ByteArrayOutputStream();
            try (var gzip = new GZIPOutputStream(bytes)) {
                gzip.write(text.getBytes(StandardCharsets.UTF_8));
            }
            try (var input = new GZIPInputStream(new ByteArrayInputStream(bytes.toByteArray()))) {
                System.out.println("[" + new String(input.readAllBytes(), StandardCharsets.UTF_8) + "]");
            }
        }
    }
}
Output
[row=2]
[]

Official Java documentation