Deflater 压缩解压

Posted light-zhang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Deflater 压缩解压相关的知识,希望对你有一定的参考价值。

import java.util.Arrays;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

import cc.zeelan.mall.common.assertion.Assert;

/**
 * 数据压缩解压
 * 
 * @project common-utils
 * @fileName StringZlibUtil.java
 * @Description
 * @author light-zhang
 * @date 2019年5月9日
 * @version 1.0.0
 */
public class CompressUtil {
    /**
     * 压缩
     * 
     * @param input  
     * @return
     */
    public static byte[] compress(byte[] input) {
        try {
            byte[] output = new byte[Integer.sum(input.length + 10,
                    Double.valueOf(Math.ceil(input.length * 0.25f)).intValue())];
            Deflater compresser = new Deflater(9);//压缩级别
            compresser.setInput(input);
            compresser.finish();
            int compressedDataLength = compresser.deflate(output);
            compresser.end();
            return Arrays.copyOf(output, compressedDataLength);
        } catch (Exception e) {
            Assert.RuntimeException("数据压缩失败");
        }
        return null;

    }

    /**
     * 解压缩
     * 
     * @param barr 须要解压缩的字节数组
     * @return
     * @throws Exception
     */
    public static byte[] uncompress(byte[] barr) {
        try {
            byte[] result = new byte[2014];
            Inflater inf = new Inflater();
            inf.setInput(barr);
            int infLen = inf.inflate(result);
            inf.end();
            return Arrays.copyOf(result, infLen);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) throws Exception {
        String str = "abcde|qqqqqqqqqqqqqqq|wwwwwwwwwwwwwwwwwwww"; 
        System.out.println("压缩前 " + str.getBytes().length);
        byte[] def = CompressUtil.compress(str.getBytes());
        System.out.println("压缩后 " + def.length);
        byte[] inf = CompressUtil.uncompress(def);
        System.out.println(new String(inf)); 
    }
}

 

以上是关于Deflater 压缩解压的主要内容,如果未能解决你的问题,请参考以下文章

Inflater 和 Deflater 解压缩中的坑

Deflater与Inflater的压缩与解压缩

Deflater压缩算法

PAT 1078. 字符串压缩与解压

1078. 字符串压缩与解压 (20)

PAT Basic 1078