StringCompressUtils.java
package javax.utils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import org.apache.commons.codec.binary.Base64; /** * Java 字符串压缩工具 * * @author Logan * @version 1.0.0 * */ public class StringCompressUtils { /** * 使用gzip进行压缩 * * @param str 压缩前的文本 * @return 返回压缩后的文本 * @throws IOException 有异常时抛出,由调用者捕获处理 */ public static String gzip(String str) throws IOException { if (str == null || str.isEmpty()) { return str; } ByteArrayOutputStream out = new ByteArrayOutputStream(); try ( GZIPOutputStream gzip = new GZIPOutputStream(out); ) { gzip.write(str.getBytes()); } return Base64.encodeBase64String(out.toByteArray()); } /** * 使用gzip进行解压缩 * * @param compressedStr 压缩字符串 * @return 解压字符串 * @throws IOException 有异常时抛出,由调用者捕获处理 */ public static String gunzip(String compressedStr) throws IOException { if (compressedStr == null || compressedStr.isEmpty()) { return compressedStr; } byte[] compressed = Base64.decodeBase64(compressedStr); ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayInputStream in = new ByteArrayInputStream(compressed); try ( GZIPInputStream ginzip = new GZIPInputStream(in); ) { byte[] buffer = new byte[4096]; int len = -1; while ((len = ginzip.read(buffer)) != -1) { out.write(buffer, 0, len); } } return out.toString(); } /** * 使用zip进行压缩 * * @param str 压缩前的文本 * @return 返回压缩后的文本 * @throws IOException 有异常时抛出,由调用者捕获处理 */ public static String zip(String str) throws IOException { if (null == str || str.isEmpty()) { return str; } ByteArrayOutputStream out = new ByteArrayOutputStream(); try ( ZipOutputStream zout = new ZipOutputStream(out); ) { zout.putNextEntry(new ZipEntry("0")); zout.write(str.getBytes()); zout.closeEntry(); } return Base64.encodeBase64String(out.toByteArray()); } /** * 使用zip进行解压缩 * * @param compressed 压缩后的文本 * @return 解压后的字符串 * @throws IOException 有异常时抛出,由调用者捕获处理 */ public static final String unzip(String compressedStr) throws IOException { if (null == compressedStr || compressedStr.isEmpty()) { return compressedStr; } byte[] compressed = Base64.decodeBase64(compressedStr); ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayInputStream in = new ByteArrayInputStream(compressed); try ( ZipInputStream zin = new ZipInputStream(in); ) { zin.getNextEntry(); byte[] buffer = new byte[4096]; int len = -1; while ((len = zin.read(buffer)) != -1) { out.write(buffer, 0, len); } } return out.toString(); } }