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

时间:2012-05-13 14:07:50

标签: java string compression

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

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

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

3 个答案:

答案 0 :(得分:25)

你可以尝试

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

答案 1 :(得分:2)

使用这个不那么复杂的解压缩函数代码可以改进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);
    }

答案 2 :(得分:0)

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

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

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

相关问题