字符串的压缩以及解压缩

2020-06-30 16:33:30 浏览数 (1)

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

代码语言:javascript复制
/**
 * @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();
	}
}

0 人点赞