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.
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.
For Base64, you have the
Base64
class from Apache Commons, and thedecodeBase64
method which takes aString
and returns abyte[]
.Then, you can read the resulting
byte[]
into aByteArrayInputStream
. At last, pass theByteArrayInputStream
to a GZipInputStream and read the uncompressed bytes.The code looks like something along these lines:
I didn't test the code, but I think it should work, maybe with a few modifications.