import lombok.extern.slf4j.Slf4j; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; /** * effect:压缩/解压 字符串 */ @Slf4j public class CompressUtils { /** * effect 使用gzip压缩字符串 * @param str 要压缩的字符串 * @return */ public static String compress(String str) { if (str == null || str.length() == 0) { return str; } ByteArrayOutputStream out = new ByteArrayOutputStream(); GZIPOutputStream gzip = null; try { gzip = new GZIPOutputStream(out); gzip.write(str.getBytes()); } catch (IOException e) { log.error("",e); } finally { if (gzip != null) { try { gzip.close(); } catch (IOException e) { log.error("",e); } } } return new sun.misc.BASE64Encoder().encode(out.toByteArray()); // return str; } /** * effect 使用gzip解压缩 * * @param str 压缩字符串 * @return */ public static String uncompress(String str) { if (str == null) { return null; } ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayInputStream in = null; GZIPInputStream ginzip = null; byte[] compressed = null; String decompressed = null; try { compressed = new sun.misc.BASE64Decoder().decodeBuffer(str); in = new ByteArrayInputStream(compressed); ginzip = new GZIPInputStream(in); byte[] buffer = new byte[1024]; int offset = -1; while ((offset = ginzip.read(buffer)) != -1) { out.write(buffer, 0, offset); } decompressed = out.toString(); } catch (IOException e) { log.error("",e); } finally { if (ginzip != null) { try { ginzip.close(); } catch (IOException e) { } } if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } return decompressed; } }