Java数据压缩与解压缩

  • 来自rocketmq源码,rocketmq中消息默认超过4KB,会进行压缩

  • evel为压缩层级,rocketmq源码中默认level为5

  • 压缩

        public static byte[] compress(final byte[] src, final int level) throws IOException {
            byte[] result = src;
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(src.length);
            java.util.zip.Deflater defeater = new java.util.zip.Deflater(level);
            DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, defeater);
            try {
                deflaterOutputStream.write(src);
                deflaterOutputStream.finish();
                deflaterOutputStream.close();
                result = byteArrayOutputStream.toByteArray();
            } catch (IOException e) {
                defeater.end();
                throw e;
            } finally {
                try {
                    byteArrayOutputStream.close();
                } catch (IOException ignored) {
                }
    
                defeater.end();
            }
    
            return result;
        }
    
  • 解压缩

    public static byte[] uncompress(final byte[] src) throws IOException {
        byte[] result = src;
        byte[] uncompressData = new byte[src.length];
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(src);
        InflaterInputStream inflaterInputStream = new InflaterInputStream(byteArrayInputStream);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(src.length);

        try {
            while (true) {
                int len = inflaterInputStream.read(uncompressData, 0, uncompressData.length);
                if (len <= 0) {
                    break;
                }
                byteArrayOutputStream.write(uncompressData, 0, len);
            }
            byteArrayOutputStream.flush();
            result = byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            throw e;
        } finally {
            try {
                byteArrayInputStream.close();
            } catch (IOException e) {
                log.error("Failed to close the stream", e);
            }
            try {
                inflaterInputStream.close();
            } catch (IOException e) {
                log.error("Failed to close the stream", e);
            }
            try {
                byteArrayOutputStream.close();
            } catch (IOException e) {
                log.error("Failed to close the stream", e);
            }
        }

        return result;
    }

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值