ByteArrayOutputStream arrayOutputStream =new ByteArrayOutputStream();
GZIPOutputStream gop = new GZIPOutputStream(arrayOutputStream);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
gop.write(buffer, 0, len);
}
gop.finish(); //这个在写入arrayOutputStream时一定要有,否则不能完全写入
gop.close;
----------------------------------------
Header encoding = method.getResponseHeader("Content-Encoding");
if (encoding != null) {
if (encoding.getValue().equals("gzip")) {
bytes = GZipUtil.unzip(bytes);
}
}
public static byte[] unzip(InputStream in) throws IOException {
// Open the compressed stream
GZIPInputStream gin = new GZIPInputStream(in);
ByteArrayOutputStream out = new ByteArrayOutputStream();
// Transfer bytes from the compressed stream to the output stream
byte[] buf = new byte[size];
int len;
while ((len = gin.read(buf)) > 0) {
out.write(buf, 0, len);
}
// Close the file and stream
gin.close();
out.close();
return out.toByteArray();
}
本文介绍如何使用Java实现GZIP格式的数据压缩与解压缩。通过ByteArrayOutputStream和GZIPOutputStream进行数据压缩,并利用GZIPInputStream完成解压缩过程。适用于网络传输等场景中减少数据体积。
1238

被折叠的 条评论
为什么被折叠?



