5

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

  • Convert.FromBase64String
  • 记忆流
  • GZipStream

这是我想转换的方法:

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);
     }
}

任何指针表示赞赏。

4

2 回答 2

5

对于 Base64,您有来自 Apache Commons的Base64 decodeBase64,以及采用 aString并返回 a的方法byte[]

然后,您可以将结果读byte[]ByteArrayInputStream. 最后,将 传递ByteArrayInputStreamGZipInputStream并读取未压缩的字节。


代码看起来像这样:

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");
}

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

于 2009-09-10T23:43:56.450 回答
1

对于 Base64,我推荐iHolder 的 implementation

GZipinputStream是解压缩 GZip 字节数组所需要的。

ByteArrayOutputStream 用于将字节写入内存。然后,您获取字节并将它们传递给字符串对象的构造函数以进行转换,最好指定编码。

于 2009-09-10T23:49:49.283 回答