1
votes

I would like a simple code to compress and decompress a String in Java. Using GZIP.

ex; String input = "Hello world";

and where the output would be a compressed string.

ex; String output = "%%#";

The requirement is to take the existing string compress it and write it on to a text file as a string. The decompression would be to read the text file and convert the content to string. Is this possible??

1
The output of Gzip is binary, not a string. How do you propose to encode the binary? - markspace
See if this answer helps: stackoverflow.com/a/19044753/1144203 - ivan.sim

1 Answers

2
votes

Yes, it's possible as a sequence of steps:

  • Convert the string to binary form, e.g. using UTF-8
  • Compress the binary data
  • Encode the binary data back as text, e.g. using base64. Do not try to "decode" it using a text encoding like base64; the result of compression is not normal encoded text.

However, unless your text is easily-compressible, the size increase due to using base64 may well mean you get a bigger string out than you put in...