5

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.

dev90
  • 7,187
  • 15
  • 80
  • 153

3 Answers3

11

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();
    }
Mohammad Zarei
  • 1,773
  • 14
  • 33
1

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

Ryan
  • 1,863
  • 13
  • 20
1
try {
     // Encode a String into bytes
     String inputString = "blahblahblah";
     byte[] input = inputString.getBytes("UTF-8");

     // Compress the bytes
     byte[] output = new byte[100];
     Deflater compresser = new Deflater();
     compresser.setInput(input);
     compresser.finish();
     int compressedDataLength = compresser.deflate(output);
     compresser.end();

     // Decompress the bytes
     Inflater decompresser = new Inflater();
     decompresser.setInput(output, 0, compressedDataLength);
     byte[] result = new byte[100];
     int resultLength = decompresser.inflate(result);
     decompresser.end();

     // Decode the bytes into a String
     String outputString = new String(result, 0, resultLength, "UTF-8");
 } catch(java.io.UnsupportedEncodingException ex) {
     // handle
 } catch (java.util.zip.DataFormatException ex) {
     // handle
 }

all code you need to ENCODE, COMPRESS , DECOMPRESS , DECODE