1

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

ccjmne
  • 9,333
  • 3
  • 47
  • 62
Learner
  • 43
  • 1
  • 9

1 Answers1

2

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

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194