java 字符串压缩工具类_Java压缩字符串工具类

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();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值