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
- Start with Text A
- Do this Compress, finish, then decompress
- Result A
Apply it to a real problem
- Start with Report row=2 and an empty report
- Do this Round-trip both through GZIP
- Result row=2 and empty text
Advertisements
Run the example
Save as Main.java and run java Main.java with JDK 21.
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) + "]");
}
}
}
}
[row=2] []