用Deflater与Inflater实现字节的压缩与解压
- - CSDN博客推荐文章* 用zip算法解压压缩字节. * @param zipByte 输入的压缩字节. * @param bytes 输入的待压缩字节. 有时在内存中需要对某些数据块实现压缩与解压,ZipInputStream / ZipOutputStream的操作对象是文件,这时就需要用到Deflater / Inflater.
package com.yangxiutian; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.zip.DataFormatException; import java.util.zip.Deflater; import java.util.zip.Inflater; public class ZLibUtils { /** * 用zip算法解压压缩字节 * @param zipByte 输入的压缩字节 * @return 解压好的解压字节 * @throws IOException */ public static byte[] decompress(byte[] zipByte) throws IOException { ByteArrayOutputStream aos=new ByteArrayOutputStream(); Inflater inflater=new Inflater(); inflater.setInput(zipByte); byte[] buff=new byte[1024]; int byteNum=0; while(!inflater.finished()){ try { byteNum=inflater.inflate(buff); aos.write(buff,0,byteNum); } catch (DataFormatException e) { e.printStackTrace(); } } return aos.toByteArray(); } /** * 用zip算法压缩字节 * @param bytes 输入的待压缩字节 * @return 压缩就绪的字节 * @throws IOException */ public static byte[] compress(byte[] bytes) throws IOException { ByteArrayOutputStream aos=new ByteArrayOutputStream(); Deflater inflater=new Deflater(); inflater.setInput(bytes); inflater.finish(); byte[] buff=new byte[1024]; int byteNum=0; while(!inflater.finished()){ byteNum=inflater.deflate(buff); aos.write(buff, 0, byteNum); } return aos.toByteArray(); } }