package com.bilibili.payplatform.utils;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.UUID;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class GZIPUtils {
public static String compress(String str) throws IOException {
if (StringUtils.isBlank(str)) {
return str;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes());
gzip.close();
String outStr = new String(Base64.encodeBase64(out.toByteArray()));
return outStr;
}
public static String uncompress(String str) throws IOException {
if (StringUtils.isBlank(str)) {
return str;
}
GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(Base64.decodeBase64(str)));
ByteArrayOutputStream out = new ByteArrayOutputStream();
IOUtils.copy(gis, out);
return new String(out.toByteArray());
}
public static void main(String[] args) throws Exception {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 500; i++) {
sb.append(UUID.randomUUID().toString() + UUID.randomUUID().toString() + UUID.randomUUID().toString());
}
String str = sb.toString();
String str1 = GZIPUtils.compress(sb.toString());
String result = GZIPUtils.uncompress(str1);
System.out.println("原長度:" + str.length());
System.out.println("壓縮後字符串:" + str1);
System.out.println("壓縮後字符串長度:" + str1.length());
System.out.println(result.equals(str));
System.out.println("解壓縮後字符串:" + result);
}
}
複製代碼