首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >字符串的压缩以及解压缩

字符串的压缩以及解压缩

作者头像
shengjk1
发布2020-06-30 16:33:30
1.2K0
发布2020-06-30 16:33:30
举报
文章被收录于专栏:码字搬砖码字搬砖

最近工作中由于表的元数据太大,准备压缩一下。具体如下:

/**
 * @author shengjk1
 * @date 2020/4/14
 */
public class Test {
	public static void main(String[] args) throws Exception {
		
		String redisHp = "localhost:5400";
		JedisCluster jedisCluster = RedisUtil.getJedisCluster(redisHp);
				
		FileInputStream fileInputStream = new FileInputStream("/Users/iss/Desktop/11111");
		String s = IOUtils.toString(fileInputStream);
////		s = s + s + s + s + s + s + s + s + s + s + s + s + s + s + s + s + s + s + s + s + s
////		;
		System.out.println("(s.getBytes().length / 1024.0) = " + (s.getBytes().length / 1024.0));
		long l = System.currentTimeMillis();
		for (int i = 0; i < 10000; i++) {
			byte[] compress = compress(s);
			System.out.println("(compress.length / 1024.0) = " + (compress.length / 1024.0));
			byte[] key = "a".getBytes("UTF-8");
			jedisCluster.set(key, compress);
			String decompress = decompress(jedisCluster.get(key));
			System.out.println(decompress.length());
		}
	}
	
	
	public static byte[] compress(String str) throws Exception {
		if (str == null || str.length() == 0) {
			return null;
		}
//		System.out.println("String length : " + str.length());
		ByteArrayOutputStream obj = new ByteArrayOutputStream();
		GZIPOutputStream gzip = new GZIPOutputStream(obj);
		gzip.write(str.getBytes("UTF-8"));
		obj.close();
		gzip.close();
		return obj.toByteArray();
	}
	
	public static String decompress(byte[] bytes) throws Exception {
		if (bytes == null || bytes.length == 0) {
			return bytes.toString();
		}
		GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes));
		BufferedReader bf = new BufferedReader(new InputStreamReader(gis, "UTF-8"));
		
		StringBuilder stringBuilder = new StringBuilder();
		String line;
		while ((line = bf.readLine()) != null) {
			stringBuilder.append(line);
		}
		
		gis.close();
		bf.close();
		return stringBuilder.toString();
	}
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-06-29 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档