aviad
aviad

Reputation: 8278

Compress and serialize String on the fly

I need to store a binary object (java class having several collections inside) in the key-value storage. The size limit for the value is 4K. I created XStream based serializer and deserializer, so when I am done filling my class members I can serialize it to a String or to a file. In the worst case the serialized String/file size is ~30K. I mange to achive good compression rate so after compression my file is ~2K which fits the bill.

My question: is there any useful java API\library\technique that can:

  1. compress a String and serialize the compressed object.
  2. decompress previously compressed object and create a regular String from it

I am looking for one-liners that do not require intermediate storage of serialized object to file for later compression.

Appreciate your help!

Upvotes: 3

Views: 2016

Answers (1)

Stijn Van Bael
Stijn Van Bael

Reputation: 4850

Try a GZIPOutputStream for zipping the String:

ByteArrayOutputStream out = new ByteArrayOutputStream();
Writer writer = new BufferedWriter(new OutputStreamWriter(new GZIPOutputStream(out)));
writer.write(string);
byte[] zipped = out.toByteArray();

And to unzip again:

ByteArrayInputStream in = new ByteArrayInputStream(zipped);
BufferedReader reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(in)));
string = reader.readLine();

Upvotes: 1

Related Questions