Java对字节数组压缩/解压
在日常的开发中,经常回遇到数据转换问题或数据参数效率问题,这时可以通过把数据进行压缩进行传输。以下是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()
来获取。
就是这么简单,你学废了吗?感觉有用的话,给笔者点个赞吧 !