Compression and Decompression of String using GZIP in java

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??

Jon Skeet
people
quotationmark

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...

people

See more on this question at Stackoverflow