简体   繁体   English

C#到Java:Base64String,MemoryStream,GZipStream

[英]C# to Java: Base64String, MemoryStream, GZipStream

I have a Base64 string that's been gzipped in .NET and I would like to convert it back into a string in Java. 我有一个在.NET中压缩过的Base64字符串,我想将其转换回Java中的字符串。 I'm looking for some Java equivalents to the C# syntax, particularly: 我正在寻找与C#语法等效的Java,尤其是:

  • Convert.FromBase64String Convert.FromBase64String
  • MemoryStream 内存流
  • GZipStream GZipStream

Here's the method I'd like to convert: 这是我想转换的方法:

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

Any pointers are appreciated. 任何指针表示赞赏。

For Base64, you have the Base64 class from Apache Commons, and the decodeBase64 method which takes a String and returns a byte[] . 对于Base64,您可以使用Apache Commons的Base64 ,还可以使用采用String并返回byte[]decodeBase64方法。

Then, you can read the resulting byte[] into a ByteArrayInputStream . 然后,您可以将结果byte[]读入ByteArrayInputStream At last, pass the ByteArrayInputStream to a GZipInputStream and read the uncompressed bytes. 最后,将ByteArrayInputStream传递给GZipInputStream并读取未压缩的字节。


The code looks like something along these lines: 这些代码看起来类似于以下几行:

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

I didn't test the code, but I think it should work, maybe with a few modifications. 我没有测试代码,但是我认为它应该可以工作,可能需要进行一些修改。

For Base64, I recommend iHolder's implementation . 对于Base64,我建议使用iHolder的实现

GZipinputStream is what you need to decompress a GZip byte array. GZipinputStream是解压缩GZip字节数组所需的。

ByteArrayOutputStream is what you use to write out bytes to memory. ByteArrayOutputStream是用于将字节写出到内存中的东西。 You then get the bytes and pass them to the constructor of a string object to convert them, preferably specifying the encoding. 然后,您获取字节并将它们传递给字符串对象的构造函数以进行转换,最好指定编码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM