Java对字节数组压缩/解压
本文共 3,034 字,预计阅读时间 10 分钟
在日常的开发中,经常回遇到数据转换问题或数据参数效率问题,这时可以通过把数据进行压缩进行传输。以下是zip、gzip的压缩和解压方法:
package com.zxh; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.zip.*; /** * @Author zxh */ public class ZxhTest { /*** * 压缩Zip * * @param data * @return */ public static byte[] zip(byte[] data) { byte[] b = null; try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ZipOutputStream zip = new ZipOutputStream(bos); ZipEntry entry = new ZipEntry("zip.txt"); entry.setSize(data.length); zip.putNextEntry(entry); zip.write(data); zip.closeEntry(); zip.close(); b = bos.toByteArray(); bos.close(); } catch (Exception ex) { ex.printStackTrace(); } return b; } /*** * 解压Zip * * @param data * @return */ public static byte[] unZip(byte[] data) { byte[] b = null; try { ByteArrayInputStream bis = new ByteArrayInputStream(data); ZipInputStream zip = new ZipInputStream(bis); while (zip.getNextEntry() != null) { byte[] buf = new byte[1024]; int num = -1; ByteArrayOutputStream baos = new ByteArrayOutputStream(); while ((num = zip.read(buf, 0, buf.length)) != -1) { baos.write(buf, 0, num); } b = baos.toByteArray(); baos.flush(); baos.close(); } zip.close(); bis.close(); } catch (Exception ex) { ex.printStackTrace(); } return b; } /*** * 压缩GZip * * @param data * @return */ public static byte[] gZip(byte[] data) { byte[] b = null; try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); GZIPOutputStream gzip = new GZIPOutputStream(bos); gzip.write(data); gzip.finish(); gzip.close(); b = bos.toByteArray(); bos.close(); } catch (Exception ex) { ex.printStackTrace(); } return b; } /*** * 解压GZip * * @param data * @return */ public static byte[] unGZip(byte[] data) { byte[] b = null; try { ByteArrayInputStream bis = new ByteArrayInputStream(data); GZIPInputStream gzip = new GZIPInputStream(bis); byte[] buf = new byte[1024]; int num = -1; ByteArrayOutputStream baos = new ByteArrayOutputStream(); while ((num = gzip.read(buf, 0, buf.length)) != -1) { baos.write(buf, 0, num); } b = baos.toByteArray(); baos.flush(); baos.close(); gzip.close(); bis.close(); } catch (Exception ex) { ex.printStackTrace(); } return b; } }
对于参数是字节数组,可以通过String的 getBytes()
来获取。
就是这么简单,你学废了吗?感觉有用的话,给笔者点个赞吧 !
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
2020-06-28 IDEA配置Maven
2020-06-28 Vue自定义表单验证
2020-06-28 VSCode基本使用
2020-06-28 TKMybatis基本用法
2020-06-28 SpringBoot常见的异常问题