Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I've been trying to figure out using GZIPOutputStream's and the like but have had no success with understanding them. All I want to do is convert a string of characters - "A string of characters" into a GZIP Base64 format. How can I do this?

By GZIP Base64 format, I mean the string is first compressed using GZIP, then converted into Base64.

like image 962
liamzebedee Avatar asked Oct 21 '11 12:10

liamzebedee


People also ask

How do I get Base64 strings?

If we were to Base64 encode a string we would follow these steps: Take the ASCII value of each character in the string. Calculate the 8-bit binary equivalent of the ASCII values. Convert the 8-bit chunks into chunks of 6 bits by simply re-grouping the digits.

What is Base64 encoding used for?

Base64 encoding schemes are commonly used when there is a need to encode binary data that needs to be stored and transferred over media that are designed to deal with ASCII. This is to ensure that the data remain intact without modification during transport.


1 Answers

Use the Apache Commons Codec Base64OutputStream.

Here's a sample class:

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 {
            Base64OutputStream b64os = new Base64OutputStream(System.out);
            GZIPOutputStream gzip = new GZIPOutputStream(b64os);
            gzip.write(text.getBytes("UTF-8"));
            gzip.close();
            b64os.close();
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}

Which outputs:

H4sIAAAAAAAAAEtUKC4pysxLV8hPU0jOSCxKTC5JLSoGAOP+cfkWAAAA

Under Linux, you can confirm this works with:

echo 'H4sIAAAAAAAAAEtUKC4pysxLV8hPU0jOSCxKTC5JLSoGAOP+cfkWAAAA' | base64 -d | gunzip

(Please note that on OSX, you should use base64 -D instead of base64 -d in the above command)

Which outputs:

a string of characters
like image 159
Dan Cruz Avatar answered Sep 21 '22 12:09

Dan Cruz