[SOLVED] How to compress a String in Android

Issue

I am trying to compress a large string object. This is what i tried, but i am unable to understand how to get compressed data, and how to define different type of compression tools.

This is what i got from Android docs.

        byte[] input = jsonArray.getBytes("UTF-8");
        byte[] output = new byte[100];

        Deflater compresser = new Deflater();
        compresser.setInput(input);
        compresser.finish();
        int compressedDataLength = compresser.deflate(output);
        compresser.end();

compresser.deflate(output) gives me a int number, 100

but i am unable to understand which method will give me the compressed output that i can send to service.

Solution

The algorithm that I compress my data with is Huffman. You can find it by a simple search. But in your case maybe it helps you:

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

And to decompress it you can use:

public static String decompress(byte[] compressed) throws IOException {
        ByteArrayInputStream bis = new ByteArrayInputStream(compressed);
        GZIPInputStream gis = new GZIPInputStream(bis);
        BufferedReader br = new BufferedReader(new InputStreamReader(gis, "UTF-8"));
        StringBuilder sb = new StringBuilder();
        String line;
        while((line = br.readLine()) != null) {
            sb.append(line);
        }
        br.close();
        gis.close();
        bis.close();
        return sb.toString();
    }

Answered By – Mohammad Zarei

Answer Checked By – Mary Flores (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *