java使用gzip压缩json数据

使用案例

public ResponseVO getListGzip() {
        List<Map<String,Object>> list = 从数据库查询数据
        try {
            return ResultUtil.success(GzipUtils.gzipByte(JSON.toJSONString(list).getBytes(StandardCharsets.UTF_8)));
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("压缩异常");
        }
    }

工具类如下


import com.google.common.io.BaseEncoding;
import com.google.common.io.Closeables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.zip.*;

public class GzipUtils {

    private static Logger logger = LoggerFactory.getLogger(GzipUtils.class);

    public static final int BUFFER = 1024;

    private static final byte[] EMPTY_BYTES = new byte[0];


    public static byte[] gzipByte(byte[] value) throws IOException {
        if (value == null) {
            return EMPTY_BYTES;
        }
        GZIPOutputStream gzipOutputStream = null;
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(value);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);
            int count;
            byte data[] = new byte[BUFFER];
            while ((count = byteArrayInputStream.read(data, 0, BUFFER)) != -1) {
                gzipOutputStream.write(data, 0, count);
            }
            gzipOutputStream.finish();
            gzipOutputStream.flush();
            return byteArrayOutputStream.toByteArray();
        } finally {
            Closeables.close(byteArrayInputStream, false);
            Closeables.close(byteArrayOutputStream, false);
            Closeables.close(gzipOutputStream, false);
        }
    }

    public static byte[] unGzipByte(byte[] bytes) throws IOException {
        if (bytes == null) {
            return EMPTY_BYTES;
        }
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream);
        try {
            int count;
            byte data[] = new byte[BUFFER];
            while ((count = gzipInputStream.read(data, 0, BUFFER)) != -1) {
                byteArrayOutputStream.write(data, 0, count);
            }
            byteArrayOutputStream.flush();
            return byteArrayOutputStream.toByteArray();
        } finally {
            Closeables.close(byteArrayOutputStream, false);
            Closeables.close(byteArrayOutputStream, false);
            Closeables.close(gzipInputStream, false);
        }
    }

    public static String unGzip(byte[] bytes) throws IOException {
        if (bytes == null) {
            return null;
        }
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream);
        try {
            int count;
            byte data[] = new byte[BUFFER];
            while ((count = gzipInputStream.read(data, 0, BUFFER)) != -1) {
                byteArrayOutputStream.write(data, 0, count);
            }
            byteArrayOutputStream.flush();
            return new String(byteArrayOutputStream.toByteArray(), "utf-8");
        } finally {
            Closeables.close(byteArrayOutputStream, false);
            Closeables.close(byteArrayOutputStream, false);
            Closeables.close(gzipInputStream, false);
        }
    }

    /**
     * 解压缩
     *
     * @param data 待压缩的数据
     * @return byte[] 解压缩后的数据
     */
    public static byte[] decompress(byte[] data) throws DataFormatException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length);
        Inflater decompresser = new Inflater();
        decompresser.reset();
        decompresser.setInput(data);

        byte[] bResult = null;
        try {
            byte[] buf = new byte[1024 * 1024];
            while (!decompresser.finished()) {
                int count = decompresser.inflate(buf);
                bos.write(buf, 0, count);
                if(count <= 0){
                    break;
                }
            }

            bResult = bos.toByteArray();
        } catch (DataFormatException e) {
            //logger.error("decompress error", e);
            throw e;
        } finally {
            decompresser.end();
            try {
                bos.close();
            } catch (IOException e) {
                //logger.error("stream close exception!", e);
            }
        }

        return bResult;
    }

    public static String decompress(String data){
        String result = null;
        try {
            byte[] bData = BaseEncoding.base64().decode(data);
            byte[] nResult = unGzipByte(bData);
            result = new String(nResult, "UTF-8");
        } catch (IOException e) {
            //logger.error("decompress error", e);
        }
        return result;
    }

    public static byte[] compress(byte[] data) {

        Deflater def = new Deflater();
        def.reset();
        def.setInput(data);
        def.finish();

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] result = null;
        try {
            byte[] buf = new byte[1024 * 1024];
            while (!def.finished()) {
                int readCount = def.deflate(buf);
                if(readCount <= 0){
                    break;
                }
                bos.write(buf, 0, readCount);
            }

            result = bos.toByteArray();
        } catch (Exception ex) {
            //logger.error("compress error", ex);
        } finally {
            try {
                bos.close();
            } catch (IOException e) {
                //logger.error("stream close exception!", e);
            }

            def.end();
        }

        return result;
    }

    public static String compress(String data) throws IOException {
        byte[] bData = null;
        try {
            bData = data.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            //logger.error("decompress UnsupportedEncodingException", e);
        }

        byte[] bResult = gzipByte(bData);
        if (bResult == null) {
            return data;
        }

        return BaseEncoding.base64().encode(bResult);
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值