实现说明
GZIP 压缩解压往返的核心是类 ReportArchive。
资源声明在 try-with-resources 头部,任何退出路径都会自动关闭,无需 finally 块。
使用要点
- 每一步打印都带着自己的标签:
original bytes:、gzipped bytes:、roundtrip equal:。
常见问题
运行「GZIP 压缩解压往返」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 original bytes:、gzipped bytes:、roundtrip equal: 这类标签。
核心语句
byte[] report = "orders=ok\norders=ok\norders=ok\n".getBytes();
ByteArrayOutputStream sink = new ByteArrayOutputStream();
byte[] compressed = sink.toByteArray();
代码示例
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());
}
}
}