用于压缩(例如 LZW)字符串的 Java 库 [英] A Java library to compress (e.g. LZW) a string

查看:31
本文介绍了用于压缩(例如 LZW)字符串的 Java 库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Apache Commons Compress 仅适用于存档文件(如果我错了,请纠正我).我需要像

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()));

LZW 只是一个例子,可以是任何类似的东西.谢谢.

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

推荐答案

你有很多选择 -

您可以使用 java.util.Deflate 算法的 Deflater

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
}

但您可能更喜欢使用流压缩器,例如带有 GZIPOutputStream.

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

如果你真的想要LZW,还有多种实现可用.

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

如果您需要更好的压缩(以速度为代价),您可能需要使用 bzip2.

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

如果您需要更高的速度(以压缩为代价),您可能需要使用 lzo.

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

这篇关于用于压缩(例如 LZW)字符串的 Java 库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆