13

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.

John Conde
  • 217,595
  • 99
  • 455
  • 496
liamzebedee
  • 14,010
  • 21
  • 72
  • 118
  • 1
    Have a look at [this question](http://stackoverflow.com/questions/6747454/problem-in-compressing-a-string-using-gzipoutputstream) – froderik Oct 21 '11 at 12:10

3 Answers3

28

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
Ashutosh Jindal
  • 18,501
  • 4
  • 62
  • 91
Go Dan
  • 15,194
  • 6
  • 41
  • 65
  • Just a small note, base64 decodes with -D. -d is used to enable debug logging. – Brandon Pelfrey Feb 16 '15 at 06:50
  • 1
    Thank you for your comment @BrandonPelfrey. Are you using Mac OS X? On Linux, the [GNU Coreutils `base64` command](https://www.gnu.org/software/coreutils/manual/coreutils.html#base64-invocation) accepts the `-d` option to decode. On [Apple Mac OS X, the `base64` command](https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/base64.1.html) accepts the `-D` option to decode. – Go Dan Feb 16 '15 at 13:38
0

Java 9

Example:

public static void main(String[] args) throws IOException {
    byte[] original = "string".getBytes(StandardCharsets.UTF_8);

    // encode
    byte[] gzipToBase64 = encodeToBase64(encodeToGZIP(original));
    System.out.println(new String(gzipToBase64));
    //H4sIAAAAAAAAACsuKcrMSwcAqbK+ngYAAAA=

    // decode
    byte[] fromBase64Gzip = decodeFromGZIP(decodeFromBase64(gzipToBase64));
    System.out.println(Arrays.equals(original, fromBase64Gzip)); //true
}
public static byte[] decodeFromBase64(byte[] arr) {
    return Base64.getDecoder().decode(arr);
}

public static byte[] encodeToBase64(byte[] arr) {
    return Base64.getEncoder().encode(arr);
}
public static byte[] decodeFromGZIP(byte[] arr) throws IOException {
    ByteArrayInputStream bais = new ByteArrayInputStream(arr);
    GZIPInputStream gzip = new GZIPInputStream(bais);
    return gzip.readAllBytes();
}

public static byte[] encodeToGZIP(byte[] arr) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream gzip = new GZIPOutputStream(baos);
    gzip.write(arr);
    gzip.finish();
    return baos.toByteArray();
}

See also: Encoding as Base64 in Java

0

This is a variation of this answer but without the deprecated stuff and using Vavr Try:

public static Try<String> compress(String input) {
  return Try.of(() -> {
    ByteArrayOutputStream rstBao = new ByteArrayOutputStream();
    GZIPOutputStream zos = new GZIPOutputStream(rstBao);
    zos.write(input.getBytes(StandardCharsets.UTF_8));
    zos.close();
    return Base64.encodeBase64String(rstBao.toByteArray());
   });

public static Try<String> decompress(String input) {
  return Try.of(() -> IOUtils.toString(new GZIPInputStream(
    new ByteArrayInputStream(Base64.decodeBase64(input))),        
      StandardCharsets.UTF_8));
  }
}

// unit test
@Test
public void testStringCompression() {
  var data = "I finally rest. And watch the sun rise on a grateful universe. The hardest choices require the strongest wills.";
  var cs = Utilities.compress(data);
  assertThat(cs.isSuccess());
  var us = Utilities.decompress(cs.get());
  assertThat(us.isSuccess() && us.get().equals(data));
}
Dexter Legaspi
  • 3,192
  • 1
  • 35
  • 26