Deflater
和GZIP
的压缩/解压实现及优缺点对比: public static String compress(String rawData) {
Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION, true); // nowrap=true
try {
deflater.setInput(rawData.getBytes(StandardCharsets.UTF_8));
deflater.finish();
try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
byte[] buffer = new byte[8192];
while (!deflater.finished()) {
int compressedBytes = deflater.deflate(buffer);
bos.write(buffer, 0, compressedBytes);
}
return Base64.getUrlEncoder().withoutPadding()
.encodeToString(bos.toByteArray());
}
} finally {
deflater.end();
}
}
public static String decompress(String compressedData) {
Inflater inflater = new Inflater(true);
try {
byte[] compressedBytes = Base64.getUrlDecoder().decode(compressedData);
inflater.setInput(compressedBytes);
try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
byte[] buffer = new byte[8192];
while (!inflater.finished()) {
try {
int decompressedBytes = inflater.inflate(buffer);
bos.write(buffer, 0, decompressedBytes);
} catch (DataFormatException e) {
throw new RuntimeException("数据损坏", e);
}
}
return bos.toString(StandardCharsets.UTF_8);
}
} finally {
inflater.end();
}
}
public static String compress(String rawData) throws IOException {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(bos)) {
gzip.write(rawData.getBytes(StandardCharsets.UTF_8));
gzip.finish();
return Base64.getEncoder().encodeToString(bos.toByteArray());
}
}
public static String decompress(String compressedData) throws IOException {
byte[] compressedBytes = Base64.getDecoder().decode(compressedData);
try (ByteArrayInputStream bis = new ByteArrayInputStream(compressedBytes);
GZIPInputStream gzip = new GZIPInputStream(bis);
ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
byte[] buffer = new byte[8192];
int len;
while ((len = gzip.read(buffer)) > 0) {
bos.write(buffer, 0, len);
}
return bos.toString(StandardCharsets.UTF_8);
}
}
特性 | Deflater (DEFLATE) | GZIP |
---|---|---|
压缩率 | ≈95%(无头部,极限压缩) | ≈93%(含18字节头部) |
速度 | 稍快(无头部开销) | 稍慢(需处理头部) |
兼容性 | 需特殊解析器 | 通用解压工具支持 |
典型应用场景 | 网络传输、内存敏感型应用 | 文件存储、通用数据交换 |
头部开销 | 无 | 18字节(含时间戳等元数据) |
校验和 | 无 | 有(CRC32) |
流式处理 | 需手动管理缓冲区 | 支持流式API |
优先选GZIP的场景:
优先选Deflater的场景:
通用原则:
实际测试显示,对于典型英文文本,Deflater比GZIP压缩率高约2-5%,但解压速度慢约10-15%。
参与评论
手机查看
返回顶部