简单测试
public static void main(String[] args) {
String str = "xxxx";
System.out.println("原串长度:"+str.length());
String s = zstdString(str);
System.out.println("zstd压缩后长度:"+s.length());
String s3 = zipString(str);
System.out.println("jdk压缩后长度:"+s3.length());
String d1 = unZstdString(s);
System.out.println(d1.equals(str));
String d3 = unzipString(s3);
System.out.println(d3.equals(str));
}
输出结果
原串长度:5974
zstd压缩后长度:3282
jdk压缩后长度:3286
true
true
zstd压缩
引入pom依赖
<dependency>
<groupId>com.github.luben</groupId>
<artifactId>zstd-jni</artifactId>
<version>1.5.4-2</version>
</dependency>
压缩/解压方法
public static String zstdString(String unzip) {
byte[] compress = Zstd.compress(unzip.getBytes());
return new sun.misc.BASE64Encoder().encodeBuffer(compress);
}
@SneakyThrows
public static String unZstdString(String zip) {
byte[] decode = new sun.misc.BASE64Decoder().decodeBuffer(zip);
Long size = Zstd.decompressedSize(decode);
byte[] decompress = Zstd.decompress(decode, size.intValue());
return new String(decompress);
}
ZLIB压缩
JDK自带,压缩/解压方法
public static String zipString(String unzip) {
Deflater deflater = new Deflater(9); // 0 ~ 9 压缩等级 低到高
deflater.setInput(unzip.getBytes());
deflater.finish();
final byte[] bytes = new byte[256];
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(256);
while (!deflater.finished()) {
int length = deflater.deflate(bytes);
outputStream.write(bytes, 0, length);
}
deflater.end();
return new sun.misc.BASE64Encoder().encodeBuffer(outputStream.toByteArray());
}
@SneakyThrows
public static String unzipString(String zip) {
byte[] decode = new sun.misc.BASE64Decoder().decodeBuffer(zip);
Inflater inflater = new Inflater();
inflater.setInput(decode);
final byte[] bytes = new byte[256];
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(256);
try {
while (!inflater.finished()) {
int length = inflater.inflate(bytes);
outputStream.write(bytes, 0, length);
}
} catch (DataFormatException e) {
e.printStackTrace();
return null;
} finally {
inflater.end();
}
return outputStream.toString();
}