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)