java Gzip入门用法

Gzip是java自带的压缩方法,虽然测试时候效率比snappy差一些,但是就我的普通的测试数据压缩率也在75%左右,对大量测试数据压缩支持也还可以。
下面介绍下压缩与解压缩byte数组的用法:

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * Created by BaoZIXI on 16/9/2.
 */
public class GzipBytes {
    private static String encode = "utf-8";//"ISO-8859-1"
    public String getEncode() {
        return encode;
    }
    //设置 编码,默认编码:UTF-8
    public void setEncode(String encode) {
        this.encode = encode;
    }

    /**
     * 压缩byte数组
     * @param bytes
     * @return byte[]
     */
    public static byte[] compressToByte(byte[] bytes){
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            GZIPOutputStream gzip;
            gzip = new GZIPOutputStream(out);
            gzip.write(bytes);
            gzip.close();
            return out.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 解压byte数组
     * @param bytes
     * @return byte[]
     */
    public static byte[] uncompress(byte[] bytes) {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ByteArrayInputStream in = new ByteArrayInputStream(bytes);
            GZIPInputStream gunzip = new GZIPInputStream(in);
            byte[] buffer = new byte[bytes.length];
            int n;
            while ((n = gunzip.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }
            return out.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

你可能感兴趣的:(随笔)