<>使用gzip对数据进行压缩、解压

我们在开发过程中,如果需要在客户端和服务器之间进行大量的数据传输操作,这种场景我们会优先考虑使用数据压缩的方式来减少传输的数据量,从而提高传输效率,以及减少客户端的运行内存等优势。

<>gzip简介

gzip是一种常用的压缩算法,它是若干种文件压缩程序的简称,通常指GNU计划的实现,此处的gzip代表GNU zip。

HTTP协议上的GZIP编码是一种用来改进WEB应用程序性能的技术。大流量的WEB站点常常使用GZIP压缩技术来让用户感受更快的速度。

<>Java中gzip压缩和解压实现

<>字节流压缩:
/** * 字节流gzip压缩 * @param data * @return */ public static byte[] gZip(byte[]
data) { byte[] b = null; try { ByteArrayInputStream in = new
ByteArrayInputStream(data); ByteArrayOutputStream out = new
ByteArrayOutputStream(); GZIPOutputStream gzip = new GZIPOutputStream(out);
byte[] buffer = new byte[4096]; int n = 0; while((n = in.read(buffer, 0,
buffer.length)) > 0){ gzip.write(buffer, 0, n); } gzip.close(); in.close(); b =
out.toByteArray(); out.close(); } catch (Exception ex) { ex.printStackTrace();
} return b; }
<>字节流解压:
/** * gzip解压 * @param data * @return */ public static byte[] unGZip(byte[]
data){ // 创建一个新的输出流 ByteArrayOutputStream out = new ByteArrayOutputStream();
try { ByteArrayInputStream in = new ByteArrayInputStream(data); GZIPInputStream
gzip = new GZIPInputStream(in); byte[] buffer = new byte[4096]; int n = 0; //
将解压后的数据写入输出流 while ((n = gzip.read(buffer)) >= 0) { out.write(buffer, 0, n); }
in.close(); gzip.close(); out.close(); } catch (Exception e) {
e.printStackTrace(); } return out.toByteArray(); }

技术
今日推荐
PPT
阅读数 135
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:766591547
关注微信