C# to Java: Base64String, MemoryStream, GZipStream
Asked Answered
D

2

5

I have a Base64 string that's been gzipped in .NET and I would like to convert it back into a string in Java. I'm looking for some Java equivalents to the C# syntax, particularly:

  • Convert.FromBase64String
  • MemoryStream
  • 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.

Dubrovnik answered 10/9, 2009 at 23:34 Comment(2)
Just a side note, does that C# code work OK ? Because you are allocating a buffer size with the length of the compressed GZip data, and then you are reading the uncompressed data to that same buffer.Impedance
The C# code above does work fine for decompressing. Thanks for your help on this one much appreciated.Dubrovnik
T
5

For Base64, you have the Base64 class from Apache Commons, and the decodeBase64 method which takes a String and returns a byte[].

Then, you can read the resulting byte[] into a ByteArrayInputStream. At last, pass the ByteArrayInputStream to a GZipInputStream and read the uncompressed bytes.


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.

Tincher answered 10/9, 2009 at 23:43 Comment(0)
F
1

For Base64, I recommend iHolder's implementation.

GZipinputStream is what you need to decompress a GZip byte array.

ByteArrayOutputStream is what you use to write out bytes to memory. You then get the bytes and pass them to the constructor of a string object to convert them, preferably specifying the encoding.

Fleurdelis answered 10/9, 2009 at 23:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.