How to compress a String in Java?

前端 未结 10 1612
一向
一向 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:10

    If you know that your strings are mostly ASCII you could convert them to UTF-8.

    byte[] bytes = string.getBytes("UTF-8");
    

    This may reduce the memory size by about 50%. However, you will get a byte array out and not a string. If you are writing it to a file though, that should not be a problem.

    To convert back to a String:

    private final Charset UTF8_CHARSET = Charset.forName("UTF-8");
    ...
    String s = new String(bytes, UTF8_CHARSET);
    

提交回复
热议问题