java如何压缩字节
使用 Deflater 类压缩字节
Java 提供了 java.util.zip.Deflater 类用于压缩字节数据。以下是一个示例代码:

import java.util.zip.Deflater;
public class ByteCompressor {
public static byte[] compress(byte[] input) {
Deflater deflater = new Deflater();
deflater.setInput(input);
deflater.finish();
byte[] buffer = new byte[input.length];
int compressedLength = deflater.deflate(buffer);
byte[] output = new byte[compressedLength];
System.arraycopy(buffer, 0, output, 0, compressedLength);
return output;
}
}
使用 Inflater 类解压缩字节
解压缩可以使用 java.util.zip.Inflater 类:

import java.util.zip.Inflater;
public class ByteDecompressor {
public static byte[] decompress(byte[] input) {
Inflater inflater = new Inflater();
inflater.setInput(input);
byte[] buffer = new byte[1024];
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
while (!inflater.finished()) {
int count = inflater.inflate(buffer);
outputStream.write(buffer, 0, count);
}
} catch (DataFormatException e) {
e.printStackTrace();
}
return outputStream.toByteArray();
}
}
使用 GZIPOutputStream 和 GZIPInputStream
对于简单的 GZIP 格式压缩:
import java.io.*;
import java.util.zip.GZIPOutputStream;
import java.util.zip.GZIPInputStream;
public class GzipCompressor {
public static byte[] compress(byte[] input) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try (GZIPOutputStream gzip = new GZIPOutputStream(bos)) {
gzip.write(input);
}
return bos.toByteArray();
}
public static byte[] decompress(byte[] input) throws IOException {
ByteArrayInputStream bis = new ByteArrayInputStream(input);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try (GZIPInputStream gzip = new GZIPInputStream(bis)) {
byte[] buffer = new byte[1024];
int len;
while ((len = gzip.read(buffer)) > 0) {
bos.write(buffer, 0, len);
}
}
return bos.toByteArray();
}
}
使用 Apache Commons Compress 库
如果需要更高级的压缩算法(如 LZ4、Brotli 等),可以使用 Apache Commons Compress:
import org.apache.commons.compress.compressors.lz4.FramedLZ4CompressorOutputStream;
import org.apache.commons.compress.compressors.lz4.FramedLZ4CompressorInputStream;
public class LZ4Compressor {
public static byte[] compress(byte[] input) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try (FramedLZ4CompressorOutputStream lz4 = new FramedLZ4CompressorOutputStream(bos)) {
lz4.write(input);
}
return bos.toByteArray();
}
public static byte[] decompress(byte[] input) throws IOException {
ByteArrayInputStream bis = new ByteArrayInputStream(input);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try (FramedLZ4CompressorInputStream lz4 = new FramedLZ4CompressorInputStream(bis)) {
byte[] buffer = new byte[1024];
int len;
while ((len = lz4.read(buffer)) > 0) {
bos.write(buffer, 0, len);
}
}
return bos.toByteArray();
}
}
注意事项
- 压缩小数据可能会产生比原始数据更大的结果,因为压缩算法有头部信息。
- 选择合适的压缩级别(
Deflater的setLevel方法)可以平衡压缩率和速度。 - 处理大文件时,建议使用流式处理而不是一次性读取全部内容到内存。
以上方法可以根据具体需求选择使用,内置的 Deflater 和 GZIP 适用于大多数场景,而第三方库如 Apache Commons Compress 提供了更多算法选择。






