Java中gzip压缩和解压(防止特殊字符解压失败,通常都是压缩后经过base64加密传输到前段)

package com.chint.kml.api.api.utils;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

@Slf4j
public abstract class XhParser {

    public static String gzip(String data) throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(out);
        gzip.write(data.getBytes());
        gzip.close();
        return new BASE64Encoder().encodeBuffer(out.toByteArray());
    }

    public static String gunzip(String compressedStr) {
        String str = null;
        if (StringUtils.isNotBlank(compressedStr)) {
            try (
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                ByteArrayInputStream in = new ByteArrayInputStream(Base64.decodeBase64(compressedStr));
                GZIPInputStream ginzip = new GZIPInputStream(in)
            ) {
                byte[] buf = new byte[1024];
                int offset = -1;
                while (-1 != (offset = ginzip.read(buf))) {
                    out.write(buf, 0, offset);
                }
                out.flush();
                str = out.toString();
            } catch (IOException e) {
                log.error("gzip解压失败,原因如下:\n{}", e.getMessage(), e);
            }
        }
        return str;
    }

    public static void main(String[] args) throws Exception {
        String uri = "C:\\Users\\xiang.gaoR\\Documents\\WeChat Files\\wxid_cjo6iua0fea322\\FileStorage\\File\\2021-05\\a.json";
        byte[] bytes = Files.readAllBytes(Paths.get(uri));
        String datas = new String(bytes);
        String realData = gunzip(datas);
        System.out.println(realData);

    }


}

 

posted @ 2021-05-20 17:37  高木子  阅读(1585)  评论(0编辑  收藏  举报