C# 到 Java : Base64String, MemoryStream、GZipStream

标签 c# java memorystream gzipstream gzipinputstream

我有一个 Base64 字符串,它在 .NET 中被压缩,我想将它转换回 Java 中的字符串。我正在寻找一些与 C# 语法等效的 Java,特别是:

  • Convert.FromBase64String
  • 内存流
  • 压缩流

这是我要转换的方法:

public static string Decompress(string zipText) {
    byte[] gzipBuff = Convert.FromBase64String(zipText);

    using (MemoryStream memstream = new MemoryStream())
    {
        int msgLength = BitConverter.ToInt32(gzipBuff, 0);
        memstream.Write(gzipBuff, 4, gzipBuff.Length - 4);

        byte[] buffer = new byte[msgLength];

        memstream.Position = 0;
        using (GZipStream gzip = new GZipStream(memstream, CompressionMode.Decompress))
        {
            gzip.Read(buffer, 0, buffer.Length);
        }
        return Encoding.UTF8.GetString(buffer);
     }
}

感谢任何指点。

最佳答案

对于 Base64,您有 Base64 class来自 Apache Commons,以及采用 String 并返回 byte[]decodeBase64 方法。

然后,您可以将生成的 byte[] 读入 ByteArrayInputStream .最后,将 ByteArrayInputStream 传递给 GZipInputStream并读取未压缩的字节。


代码看起来像这样:

public static String Decompress(String zipText) throws IOException {
    byte[] gzipBuff = Base64.decodeBase64(zipText);

    ByteArrayInputStream memstream = new ByteArrayInputStream(gzipBuff);
    GZIPInputStream gzin = new GZIPInputStream(memstream);

    final int buffSize = 8192;
    byte[] tempBuffer = new byte[buffSize ];
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    while ((size = gzin.read(tempBuffer, 0, buffSize)) != -1) {
        baos.write(tempBuffer, 0, size);
    }        
    byte[] buffer = baos.toByteArray();
    baos.close();

    return new String(buffer, "UTF-8");
}

我没有测试代码,但我认为它应该可以工作,也许需要一些修改。

关于C# 到 Java : Base64String, MemoryStream、GZipStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1408267/

相关文章:

c# - 在 Metro 应用程序 C# 中重新加载页面

c# - 抑制关于 :blank in Print Output of WinForms WebBrowser

c# - XML反序列化问题(带有命名空间的属性)

c#: BaseClass 虚方法使用在子类中定义的对象

java - 如何告诉 htmlunit 忽略某些错误

c# - 在 c# wpf 中从 Memorystream 获取图像源

Java 非静态方法 addInv(int) 无法从静态上下文中引用

java - 如何在 BottomSheetDialogFragment 内的 ViewPager2 上启用拖动?

node.js - Node js,将pdfkit管道传输到内存流

.net - 为什么这个简单的 MemoryStream.Write() 实验失败了?