packagejavax.utils;importjava.io.ByteArrayInputStream;importjava.io.ByteArrayOutputStream;importjava.io.IOException;importjava.util.zip.GZIPInputStream;importjava.util.zip.GZIPOutputStream;importjava.util.zip.ZipEntry;importjava.util.zip.ZipInputStream;importjava.util.zip.ZipOutputStream;importorg.apache.commons.codec.binary.Base64;/*** Java 字符串压缩工具
*
*@authorLogan
*@version1.0.0
**/
public classStringCompressUtils {/*** 使用gzip进行压缩
*
*@paramstr 压缩前的文本
*@return返回压缩后的文本
*@throwsIOException 有异常时抛出,由调用者捕获处理*/
public static String gzip(String str) throwsIOException {if (str == null ||str.isEmpty()) {returnstr;
}
ByteArrayOutputStream out= newByteArrayOutputStream();try(
GZIPOutputStream gzip= newGZIPOutputStream(out);
) {
gzip.write(str.getBytes());
}returnBase64.encodeBase64String(out.toByteArray());
}/*** 使用gzip进行解压缩
*
*@paramcompressedStr 压缩字符串
*@return解压字符串
*@throwsIOException 有异常时抛出,由调用者捕获处理*/
public static String gunzip(String compressedStr) throwsIOException {if (compressedStr == null ||compressedStr.isEmpty()) {returncompressedStr;
}byte[] compressed =Base64.decodeBase64(compressedStr);
ByteArrayOutputStream out= newByteArrayOutputStream();
ByteArrayInputStream in= newByteArrayInputStream(compressed);try(
GZIPInputStream ginzip= newGZIPInputStream(in);
) {byte[] buffer = new byte[4096];int len = -1;while ((len = ginzip.read(buffer)) != -1) {
out.write(buffer,0, len);
}
}returnout.toString();
}/*** 使用zip进行压缩
*
*@paramstr 压缩前的文本
*@return返回压缩后的文本
*@throwsIOException 有异常时抛出,由调用者捕获处理*/
public static String zip(String str) throwsIOException {if (null == str ||str.isEmpty()) {returnstr;
}
ByteArrayOutputStream out= newByteArrayOutputStream();try(
ZipOutputStream zout= newZipOutputStream(out);
) {
zout.putNextEntry(new ZipEntry("0"));
zout.write(str.getBytes());
zout.closeEntry();
}returnBase64.encodeBase64String(out.toByteArray());
}/*** 使用zip进行解压缩
*
*@paramcompressed 压缩后的文本
*@return解压后的字符串
*@throwsIOException 有异常时抛出,由调用者捕获处理*/
public static final String unzip(String compressedStr) throwsIOException {if (null == compressedStr ||compressedStr.isEmpty()) {returncompressedStr;
}byte[] compressed =Base64.decodeBase64(compressedStr);
ByteArrayOutputStream out= newByteArrayOutputStream();
ByteArrayInputStream in= newByteArrayInputStream(compressed);try(
ZipInputStream zin= newZipInputStream(in);
) {
zin.getNextEntry();byte[] buffer = new byte[4096];int len = -1;while ((len = zin.read(buffer)) != -1) {
out.write(buffer,0, len);
}
}returnout.toString();
}
}