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)); 
    }
}
相關文章
相關標籤/搜索