zstd字符串压缩

简单测试

	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();
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值