How to compress a String in Java?

前端 未结 10 1611
一向
一向 2020-11-28 05:28

I use GZIPOutputStream or ZIPOutputStream to compress a String (my string.length() is less than 20), but the compressed result is long

10条回答
  •  悲&欢浪女
    2020-11-28 06:18

    Your friend is correct. Both gzip and ZIP are based on DEFLATE. This is a general purpose algorithm, and is not intended for encoding small strings.

    If you need this, a possible solution is a custom encoding and decoding HashMap. This can allow you to do a simple one-to-one mapping:

    HashMap toCompressed, toUncompressed;
    
    String compressed = toCompressed.get(uncompressed);
    // ...
    String uncompressed = toUncompressed.get(compressed);
    

    Clearly, this requires setup, and is only practical for a small number of strings.

提交回复
热议问题