Java C# GZip 字符串压缩解压

本贴最后更新于 2674 天前,其中的信息可能已经渤澥桑田

压缩:将指定的原字符串用 gzip 算法压缩,然后以 BASE64 编码
解压:将指定的 BASE64 编码的字符串用 gzip 解压,返回原字符串

原字符串为 UTF-8 编码。

Java 版本

导入包

基本都是 JDK 内置的包,BASE64 部分可能需要替换一下(JDK8 已经自带 BASE64)。

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.codec.binary.Base64;

实现部分

/**
 * 使用 gzip 进行压缩.
 *
 * @param str 压缩前的文本
 * @return 压缩后的文本(BASE64 编码)
 * @throws IOException 如果解压异常
 */
public static String gzip(final String str) throws IOException {
    if (str == null || "".equals(str)) {
        return str;
    }

    String ret = null;

    byte[] compressed;
    ByteArrayOutputStream out = null;
    GZIPOutputStream zout = null;
    try {
        out = new ByteArrayOutputStream();
        zout = new GZIPOutputStream(out);
        zout.write(str.getBytes());
        zout.close();
        compressed = out.toByteArray();
        ret = new String(Base64.encodeBase64(compressed), "UTF-8");
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }
    }

    return ret;
}

/**
 * 使用 gzip 进行解压缩.
 *
 * @param compressedStr 压缩后的文本(BASE64 编码)
 * @return 解压后的文本
 * @throws IOException 如果解压异常
 */
public static String ungzip(final String compressedStr) throws IOException {
    if (null == compressedStr || "".equals(compressedStr)) {
        return compressedStr;
    }

    String ret = null;

    ByteArrayOutputStream out = null;
    ByteArrayInputStream in = null;
    GZIPInputStream zin = null;
    try {
        final byte[] compressed = Base64.decodeBase64(compressedStr);
        out = new ByteArrayOutputStream();
        in = new ByteArrayInputStream(compressed);
        zin = new GZIPInputStream(in);
        final byte[] buffer = new byte[1024];
        int offset = -1;
        while ((offset = zin.read(buffer)) != -1) {
            out.write(buffer, 0, offset);
        }

        ret = out.toString("UTF-8");
    } finally {
        if (zin != null) {
            try {
                zin.close();
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }
        if (in != null) {
            try {
                in.close();
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }
    }

    return ret;
}

C# 版本

命名空间

using System;
using System.Text;
using System.IO;
using System.IO.Compression;

实现部分

/// <summary>
/// 使用 gzip 进行压缩
/// </summary>
/// <param name="str">压缩前的文本</param>
/// <returns>压缩后的文本(BASE64 编码)</returns>
public static string gzip(string str)
{
    if (null == str || "".Equals(str))
    {
        return str;
    }

    byte[] buffer = Encoding.UTF8.GetBytes(str);
    MemoryStream ms = new MemoryStream();
    using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true))
    {
        zip.Write(buffer, 0, buffer.Length);
    }

    return Convert.ToBase64String(ms.ToArray());
}

/// <summary>
/// 使用 gzip 进行解压缩
/// </summary>
/// <param name="compressedStr">压缩后的文本(BASE64 编码)</param>
/// <returns>解压后的文本</returns>
public static string ungzip(string compressedStr)
{
    if (null == compressedStr || "".Equals(compressedStr))
    {
        return compressedStr;
    }

    using (var compressedStream = new MemoryStream(Convert.FromBase64String(compressedStr)))
    using (var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress))
    using (var resultStream = new MemoryStream())
    {
        var buffer = new byte[4096 * 2];
        int read;

        while ((read = zipStream.Read(buffer, 0, buffer.Length)) > 0)
        {
            resultStream.Write(buffer, 0, read);
        }

        return Encoding.UTF8.GetString(resultStream.ToArray());
    }
}

Unity

如果 C# 版要用在 Unity 上,则需要安装这个免费插件,再将引入的命名空间从 System.IO.Compression 改为 Unity.IO.Compression 即可。


姊妹篇: https://hacpai.com/article/1481701879422

  • Gzip

    gzip (GNU zip)是 GNU 自由软件的文件压缩程序。我们在 Linux 中经常会用到后缀为 .gz 的文件,它们就是 Gzip 格式的。现今已经成为互联网上使用非常普遍的一种数据压缩格式,或者说一种文件格式。

    9 引用 • 12 回帖 • 106 关注
  • Java

    Java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由 Sun Microsystems 公司于 1995 年 5 月推出的。Java 技术具有卓越的通用性、高效性、平台移植性和安全性。

    3165 引用 • 8206 回帖
  • Unity

    Unity 是由 Unity Technologies 开发的一个让开发者可以轻松创建诸如 2D、3D 多平台的综合型游戏开发工具,是一个全面整合的专业游戏引擎。

    25 引用 • 7 回帖 • 249 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...
  • Eddie

    消灭零回复

  • sides

    3ddba74cceb94a27a3dfb94e67230711-IMG0979.JPG

  • smart

    尽量不要直接 e.printStackTrace();哦😄

    1 回复
  • 88250

    嗯,实例代码仅供参考。

  • zonghua

    😂 发现 Spring 默认没有提供 Gzip 的消息转换器,没法实现接受 gzip 请求,自定义拦截器好像没法改输入流。