How can I convert a string into a GZIP Base64 string?
Asked Answered
M

3

14

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.

Manassas answered 21/10, 2011 at 12:0 Comment(1)
Have a look at this questionAffective
H
31

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
Horribly answered 21/10, 2011 at 12:33 Comment(2)
Just a small note, base64 decodes with -D. -d is used to enable debug logging.Clubman
Thank you for your comment @BrandonPelfrey. Are you using Mac OS X? On Linux, the GNU Coreutils base64 command accepts the -d option to decode. On Apple Mac OS X, the base64 command accepts the -D option to decode.Horribly
G
1

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

Gidgetgie answered 28/2, 2021 at 13:29 Comment(0)
P
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));
}
Phail answered 23/4, 2021 at 18:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.