Java压缩byte数组
时间: 2023-09-14 11:09:16 浏览: 52
您可以使用 Java 中的 GZIP 压缩算法来压缩 byte 数组。以下是一个示例代码:
```java
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class ByteArrayCompression {
public static byte[] compress(byte[] data) throws Exception {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(bos);
gzip.write(data);
gzip.close();
byte[] compressed = bos.toByteArray();
bos.close();
return compressed;
}
public static byte[] decompress(byte[] compressed) throws Exception {
ByteArrayInputStream bis = new ByteArrayInputStream(compressed);
GZIPInputStream gzip = new GZIPInputStream(bis);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = gzip.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
gzip.close();
bos.close();
byte[] decompressed = bos.toByteArray();
return decompressed;
}
}
```
您可以使用 `compress` 方法来压缩 byte 数组,使用 `decompress` 方法来解压缩 byte 数组。