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

9.5k views Asked by At

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.

2

There are 2 answers

1
Elliott Frisch On BEST ANSWER

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.

1
Tim B On

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?