java bzip2压缩是一个比gzip压缩率更高的压缩形式,使用了BZip2CompressorOutputStream类来将json等数据压缩并输出,本案例是一个写好了的bzip2压缩与解压缩工具类,使用bzip2压缩要导入commons-compress相关的jar包,如下:
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-compress</artifactId> <version>1.5</version> </dependency>
新建一个Bzip2Utils.java工具类,在里面定义好bzip2压缩与解压缩的静态方法,如下:
package demo; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream; import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream; public class Bzip2Utils { //bzip2压缩方法 public static byte[] bzipCompress(byte[] data) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); BZip2CompressorOutputStream bcos = new BZip2CompressorOutputStream(out); try { bcos.write(data); } finally { bcos.close(); out.close(); } return out.toByteArray(); } //bzip2解压方法 public static byte[] bzipUncompress(byte[] data) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayInputStream in = new ByteArrayInputStream(data); BZip2CompressorInputStream ungzip = new BZip2CompressorInputStream(in); try { byte[] buffer = new byte[1024]; int n; while ((n = ungzip.read(buffer)) >= 0) { out.write(buffer, 0, n); } } finally { ungzip.close(); in.close(); out.close(); } return out.toByteArray(); } }
在main方法中测试bzip2压缩与bzip2解压缩数据,如下:
public static void main(String[] args) throws Exception { String queryString = "{ firstName:Bill测试 , lastName:Gates }{ firstName:Bill , lastName:Gates }"; for (int i = 0; i < 10; i++) { queryString = queryString + queryString; } System.out.println("压缩前长度:"+queryString.length()); byte[] zip = Bzip2Utils.bzipCompress(queryString.getBytes()); System.out.println("压缩后长度:"+zip.length); //byte[] bys = Bzip2Utils.bzipUncompress(zip); //System.out.println(new String(bys,"UTF-8")); }
输出结果如下,gzip压缩率很高,比gzip更好:
压缩前长度:73728 压缩后长度:147