code
package com.xcg.webapp.Common; import org.apache.commons.lang3.StringUtils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; public class GZipUtil { /** * gzip压缩 * */ public static String gzipCompress(String text) { if (StringUtils.isEmpty(text)) { return null; } java.io.ByteArrayOutputStream byteArrayOutputStream = new java.io.ByteArrayOutputStream(); try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream)) { gzipOutputStream.write(text.getBytes(StandardCharsets.UTF_8)); gzipOutputStream.flush(); gzipOutputStream.finish(); } catch (Exception e) { System.out.println(e); return null; } return Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray()); } /** * gzip解压缩 * */ public static String gzipUnCompress(String compressedStr) { if (compressedStr == null) { return null; } ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayInputStream in = null; GZIPInputStream ginzip = null; byte[] compressed = null; String decompressed = null; try { byte[] encodedBytes = compressedStr.getBytes(StandardCharsets.UTF_8); compressed = Base64.getDecoder().decode(encodedBytes); 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) { e.printStackTrace(); } finally { if (ginzip != null) { try { ginzip.close(); } catch (IOException e) { } } if (in != null) { try { in.close(); } catch (IOException e) { } } try { out.close(); } catch (IOException e) { } } return decompressed; } }