如何轻松地将字符串压缩和解压缩到字节数组?

我有一些字符串,每个字符串大约10K字符。 它们有很多重复。 它们是序列化的JSON对象。 我想轻松地将它们压缩成字节数组,并从字节数组中解压缩它们。

我怎样才能最轻松地做到这一点? 我正在寻找方法,所以我可以做到以下几点:

String original = "....long string here with 10K characters..."; byte[] compressed = StringCompressor.compress(original); String decompressed = StringCompressor.decompress(compressed); assert(original.equals(decompressed); 

你可以试试

 enum StringCompressor { ; public static byte[] compress(String text) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { OutputStream out = new DeflaterOutputStream(baos); out.write(text.getBytes("UTF-8")); out.close(); } catch (IOException e) { throw new AssertionError(e); } return baos.toByteArray(); } public static String decompress(byte[] bytes) { InputStream in = new InflaterInputStream(new ByteArrayInputStream(bytes)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { byte[] buffer = new byte[8192]; int len; while((len = in.read(buffer))>0) baos.write(buffer, 0, len); return new String(baos.toByteArray(), "UTF-8"); } catch (IOException e) { throw new AssertionError(e); } } } 

使用这种不那么复杂的解压缩函数代码可以改进Peter Lawrey的答案

  ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { OutputStream out = new InflaterOutputStream(baos); out.write(bytes); out.close(); return new String(baos.toByteArray(), "UTF-8"); } catch (IOException e) { throw new AssertionError(e); } 

我创建了一个库来解决压缩generics字符串(特别是短字符串)的问题。 它尝试使用各种算法压缩字符串(普通的utf-8,5位编码用于拉丁字母,霍夫曼编码,gzip用于长字符串)并选择具有最短结果的字符串(在最坏的情况下,它将选择utf-8)编码,这样你就不会冒失去空间的风险)。

我希望它可能有用,这是链接https://github.com/lithedream/lithestring

编辑:我意识到你的字符串总是“长”,我的库默认使用gzip这些大小,我担心我不能为你做得更好。