Java – How to convert a string into a GZIP Base64 string? and reversaly?

In this post, I want to show how to convert human readible String to gzipped base64 String and reversaly.

GzipUtil.java

package com.gayratrakhimov.gzipsandbox;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GzipUtil {

    public static byte[] compress(String string) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream(string.length());
        GZIPOutputStream gos = new GZIPOutputStream(os);
        gos.write(string.getBytes());
        gos.close();
        byte[] compressed = os.toByteArray();
        os.close();
        return compressed;
    }

    public static String decompress(byte[] compressed) throws IOException {
        final int BUFFER_SIZE = 32;
        ByteArrayInputStream is = new ByteArrayInputStream(compressed);
        GZIPInputStream gis = new GZIPInputStream(is, BUFFER_SIZE);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] data = new byte[BUFFER_SIZE];
        int bytesRead;
        while ((bytesRead = gis.read(data)) != -1) {
            baos.write(data, 0, bytesRead);
        }
        gis.close();
        return baos.toString("UTF-8");
    }

}

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        encode();
        decode();

    }

    // String(human readible)->compress as gzip->String(base64 format)
    private void encode(){

        try {
            String textToEncode = "Hello";
            byte[] compressed = GzipUtil.compress(textToEncode);
            String result = Base64.encodeToString(compressed, Base64.DEFAULT);
            Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //String(base64 format)->decompress zip->String(human readible)
    private void decode(){

        try {
            String textToDecode = "H4sIAAAAAAAAAPNIzcnJBwCCidH3BQAAAA==\n";
            byte[] data = Base64.decode(textToDecode, Base64.DEFAULT);
            String result = GzipUtil.decompress(data);
            Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
   
}