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

Ste*_*eod 10 java compression string

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

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

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

Pet*_*rey 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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 有些人喜欢使用枚举类作为实现单例或静态类的方法.由Effective Java撰稿人Joshua Bloch推荐. (6认同)
  • 您好,为什么在这里使用`enum`而不是`class`?这是证明一点吗? (2认同)
  • @Matthieu您可以使用ISO-8859-1编码在字符串中存储字节而不会丢失。 (2认同)