gzip and base64 in Java

December 27th, 2006

I recently had to gzip and base64 encode data before sending it via XML-RPC calls over the network, which took a bit of researching.

Java has built in support for gzip via java.util.zip.GZIPInputStream and java.util.zip.GZIPOutputStream. While there is no official Java base 64 encoder and decoder there are a couple of undocumented classes called sun.misc.BASE64Encoder and sun.misc.BASE64Decoder which seem to work fine.

Below are a couple of examples of turning the contents of a reader into gzipped base64 encoded data and turning a string containing base64 encoded gzipped data back into normal text (exceptions and comments omitted).

public String encode(BufferedReader input) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    OutputStreamWriter writer = new OutputStreamWriter(new GZIPOutputStream(out));
    char[] charBuffer = new char[1024]; 
    while(input.read(charBuffer) != -1) {
        writer.write(charBuffer);
    }
    writer.close();
    return (new BASE64Encoder()).encode(out.toByteArray());
}
public String decode(String input) throws Exception {
    byte[] bytes = (new BASE64Decoder()).decodeBuffer(input);
    BufferedReader in = new BufferedReader(new InputStreamReader(
            new GZIPInputStream(new ByteArrayInputStream(bytes))));
    StringBuffer buffer = new StringBuffer();
    char[] charBuffer = new char[1024]; 
    while(in.read(charBuffer) != -1) {
        buffer.append(charBuffer);
    }
    return buffer.toString();
}

Sorry, comments are closed for this article.