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);
    
        }
    
    
    }
    既然我已经踏上这条道路,那么,任何东西都不应妨碍我沿着这条路走下去!!!!!!!!!! !!! ! !! ! 个人公众号《后端技术开发之路》,欢迎您关注!

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

  • 相关阅读:
    新闻
    蜂群
    Quartz.NET的管理工具
    安卓手机开发的学习资料
    Android IOS WebRTC 音视频开发总结(十九)- kurento
    WebRTC实现很难?让我们看看Mozilla是如何做的
    WebRTC流媒体服务器 Kurento
    Webrtc服务器搭建
    crtmpserver组网部署方案
    实现输出h264直播流的rtmp服务器
  • 原文地址:https://www.cnblogs.com/gaomanito/p/14790795.html
Copyright © 2011-2022 走看看