zoukankan      html  css  js  c++  java
  • 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解压失败,原因如下:
    {}", 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);
    
        }
    
    
    }
    既然我已经踏上这条道路,那么,任何东西都不应妨碍我沿着这条路走下去!!!!!!!!!! !!! ! !! ! 个人公众号《后端技术开发之路》,欢迎您关注!

    如果您觉得我写还不过,请打赏下在下吧!【高木子】!

  • 相关阅读:
    JZOJ 2548. 【NOIP2011模拟9.4】最大正方形
    JZOJ 3532. 【NOIP2013提高组day1】转圈游戏
    网络流模板 dinic
    1433: [ZJOI2009]假期的宿舍
    JZOJ 1285. 奶酪厂
    JZOJ 1284. 病毒
    SpringMVC路径匹配规则源码
    RESTful设计风格下SpringMVC的URI设计性能问题
    递归查询mysql数据库设计
    java定时任务调度
  • 原文地址:https://www.cnblogs.com/gaomanito/p/14790795.html
Copyright © 2011-2022 走看看