C# to Java: Base64String, MemoryStream, GZipStream

不羁岁月 提交于 2019-12-04 07:14:15
João Silva

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!