gzip压缩接口数据工具

最新需要提供一个文本数据交换的接口,由于数据量比较大,需要对数据进行压缩传输,节省流量,所以写了一个使用Gzip进行数据压缩的小公举。

代码:

public class GzipUtil {

    /**
     * 压缩数据
     * @param bytes
     * @return
     * @throws IOException
     */
    public static byte[] compress(byte[] bytes) throws IOException{

        try (ByteArrayOutputStream out = new ByteArrayOutputStream();
             GZIPOutputStream gzip = new GZIPOutputStream(out)){
            gzip.write(bytes);
            gzip.close();
            return out.toByteArray();
        }
    }

    /**
     * gzip压缩字符串
     * @param content
     * @param charset
     * @return
     * @throws IOException
     */
    public static byte[] compress(String content, String charset) throws IOException {

        Assert.notNull(content, "null content error");
        return compress(content.getBytes(charset));
    }

    /**
     * gizp解压
     * @param in
     * @return
     * @throws IOException
     */
    public static byte[] uncompress(InputStream in) throws IOException {

        try(ByteArrayOutputStream out = new ByteArrayOutputStream();
            GZIPInputStream gin = new GZIPInputStream(in)){
            byte[] buffer = new byte[1024];
            int len;
            while ((len = gin.read(buffer)) >= 0){
                out.write(buffer, 0 ,len);
            }
            return out.toByteArray();
        }
    }

    /**
     * 解压缩为字符串
     * @param in
     * @param charset
     * @return
     * @throws IOException
     */
    public static String uncompress(InputStream in, String charset) throws IOException {

        byte[] bytes = uncompress(in);
        return new String(bytes, charset);
    }
}

工具测试:

@Test
public void test(){
        try {
            byte[] xiyouji = Files.readAllBytes(Paths.get("西游记.txt"));

            System.out.println("压缩前体积:" + xiyouji.length/1024 + "k");

            byte[] compress = GzipUtil.compress(xiyouji);
            System.out.println("压缩后体积:" + compress.length/1024 + "k");

            byte[] uncompress = GzipUtil.uncompress(new ByteArrayInputStream(compress));
            System.out.println("解压后体积:" + uncompress.length/1024 + "k");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

测试结果:

压缩前体积:2102k
压缩后体积:935k
解压后体积:2102k
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值