Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compress a String in Android

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.

like image 556
dev90 Avatar asked Mar 09 '23 04:03

dev90


2 Answers

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();
    }
like image 104
Mohammad Zarei Avatar answered Mar 19 '23 07:03

Mohammad Zarei


The documentation for Deflator shows that the output gets put into the buffer output

like image 27
Ryan Avatar answered Mar 19 '23 08:03

Ryan