GZIP Roundtrip Compress And Decompress

Compress bytes with GZIPOutputStream and read them back with GZIPInputStream, verifying a byte-exact roundtrip and the failure path for non-gzip input.

JavaData Integrity

Code

snippet
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class ReportArchive {

    public static void main(String[] args) throws IOException {
        byte[] report = "orders=ok\norders=ok\norders=ok\n".getBytes();

        // 压缩 compress:GZIPOutputStream 必须 close(或 finish),gzip trailer 才写完整
        ByteArrayOutputStream sink = new ByteArrayOutputStream();
        try (var gzip = new GZIPOutputStream(sink)) {
            gzip.write(report);
        }
        byte[] compressed = sink.toByteArray();
        System.out.println("original bytes: " + report.length);
        System.out.println("gzipped bytes:  " + compressed.length);

        // 解压 decompress:同一 payload 逐字节还原
        byte[] restored;
        try (var in = new GZIPInputStream(new ByteArrayInputStream(compressed))) {
            restored = in.readAllBytes();
        }
        System.out.println("roundtrip equal: " + Arrays.equals(report, restored));

        // 不是 gzip 容器的输入直接抛 IOException(Not in GZIP format)
        try (var in = new GZIPInputStream(new ByteArrayInputStream("plain".getBytes()))) {
            in.readAllBytes();
        } catch (IOException notGzip) {
            System.out.println("bad payload -> " + notGzip.getMessage());
        }
    }
}

Inside the snippet

GZIP Roundtrip Compress And Decompress reduces to the class ReportArchive.

No finally block here — resources declared in the try header close themselves in reverse order.

Putting it to use

Running the file prints labeled results such as original bytes:, gzipped bytes:, roundtrip equal: — each operation’s effect is visible in the output.

Core lines

byte[] report = "orders=ok\norders=ok\norders=ok\n".getBytes();
ByteArrayOutputStream sink = new ByteArrayOutputStream();
byte[] compressed = sink.toByteArray();

Interactive Tools for This Topic

FAQ

What does GZIP Roundtrip Compress And Decompress print when run?
Run it as a complete program — the output lines carry labels such as `original bytes:`, `gzipped bytes:`, `roundtrip equal:`.