A Java library to compress (e.g. LZW) a string

回眸只為那壹抹淺笑 提交于 2019-12-08 05:23:10

问题


Apache Commons Compress works only with archive files (please correct me if I am wrong). I need something like

MyDB.put(LibIAmLookingFor.compress("My long string to store"));
String getBack = LibIAmLookingFor.decompress(MyDB.get()));

And LZW is just an example, could be anything similar. Thank you.


回答1:


You have a plethora of choices -

You can use the java.util.Deflater for the Deflate algortihm,

try {
  // Encode a String into bytes
  String inputString = "blahblahblah??";
  byte[] input = inputString.getBytes("UTF-8");

  // Compress the bytes
  byte[] output = new byte[100];
  Deflater compresser = new Deflater();
  compresser.setInput(input);
  compresser.finish();
  int compressedDataLength = compresser.deflate(output);

  // Decompress the bytes
  Inflater decompresser = new Inflater();
  decompresser.setInput(output, 0, compressedDataLength);
  byte[] result = new byte[100];
  int resultLength = decompresser.inflate(result);
  decompresser.end();

  // Decode the bytes into a String
  String outputString = new String(result, 0, resultLength, "UTF-8");
} catch(java.io.UnsupportedEncodingException ex) {
   // handle
} catch (java.util.zip.DataFormatException ex) {
   // handle
}

But you may prefer to use a streaming compressor, like gzip with a GZIPOutputStream.

If you really want LZW, there are multiple implementations available.

If you need even better compression (at the cost of speed), you may want to use bzip2.

If you need even more speed (at the cost of compression), you may want to use lzo.




回答2:


Java has libraries built in for ZIP compression:

http://docs.oracle.com/javase/6/docs/api/java/util/zip/package-summary.html

Will that do what you need?



来源:https://stackoverflow.com/questions/20830918/a-java-library-to-compress-e-g-lzw-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!