Java byte数组压缩
时间: 2023-09-14 11:09:18 浏览: 46
Java中可以使用GZIP或者Deflater类来对byte数组进行压缩。
使用GZIP进行压缩:
```java
public static byte[] compress(byte[] data) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length);
GZIPOutputStream gzip = new GZIPOutputStream(bos);
gzip.write(data);
gzip.close();
byte[] compressed = bos.toByteArray();
bos.close();
return compressed;
}
```
使用Deflater进行压缩:
```java
public static byte[] compress(byte[] data) throws IOException {
Deflater deflater = new Deflater();
deflater.setInput(data);
deflater.finish();
ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length);
byte[] buffer = new byte[1024];
while (!deflater.finished()) {
int count = deflater.deflate(buffer);
bos.write(buffer, 0, count);
}
deflater.end();
byte[] compressed = bos.toByteArray();
bos.close();
return compressed;
}
```
以上两种方式都是对byte数组进行压缩,返回的是压缩后的byte数组。需要注意的是,解压缩时需要使用相应的解压缩方法。