编程语言
首页 > 编程语言> > C#到Java:Base64String,MemoryStream,GZipStream

C#到Java:Base64String,MemoryStream,GZipStream

作者:互联网

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

> Convert.FromBase64String
> MemoryStream
> 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);
     }
}

任何指针都表示赞赏.

解决方法:

对于Base64,您拥有Apache Commons的Base64 class和带有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,memorystream,gzipstream,gzipinputstream
来源: https://codeday.me/bug/20190622/1259920.html