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

前端 未结 2 635
被撕碎了的回忆
被撕碎了的回忆 2020-12-28 09:56

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 char

相关标签:
2条回答
  • 2020-12-28 10:11

    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
    
    0 讨论(0)
  • 2020-12-28 10:26

    We can use Java GZIPOutputStream/GZIInputStream and apache commons codec Base64 Encoder and Decoder:lifelongprogrammer.blogspot.com

    0 讨论(0)
提交回复
热议问题