How can I convert a string into a GZIP Base64 string with ByteArrayOutputStream?

2.1k views Asked by At

I need to convert string to gzip base64. I have this code

import java.util.zip.GZIPOutputStream;
import org.apache.commons.codec.binary.Base64OutputStream;

public class Test {
    public static void main(String[] args) {
        String text = "a string of characters";
        try {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            Base64OutputStream b64os = new Base64OutputStream(os);
            GZIPOutputStream gzip = new GZIPOutputStream(b64os);
            gzip.write(text.getBytes("UTF-8"));
            String base64 = new String(os.toByteArray(),"UTF-8");
            gzip.close();
            b64os.close();
            System.out.print(base64)
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}

I need get H4sIAAAAAAAAAEtUKC4pysxLV8hPU0jOSCxKTC5JLSoGAOP+cfkWAAAA. Why did I get this output?

H4sIAAAAAAAA
1

There are 1 answers

0
Jon Skeet On

You're calling os.toByteArray() before you've closed gzip and b64os - which means they've almost certainly got buffered data. (Aside from anything else, a base64 stream has to wait until it's closed to write out any padding.)

Just move the declaration/assignment of base64 to after the close calls, and I suspect it'll be fine.