java字符原地压缩_Java字符串压缩

java 压缩字符串

如果源字符串长度小于64,压缩后的字符会比源字符串长。

例如:

str.length()=32

compressedStr.length()=36

/**

* 压缩字符串

* @param str 要压缩的字符串

* @return 压缩后的字符串

*/

public static String compress(String str) {

if (str == null || str.length() == 0) {

return str;

}

GZIPOutputStream gzipOutputStream=null;

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

try {

gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);

gzipOutputStream.write(str.getBytes());

} catch (IOException e) {

e.printStackTrace();

} finally {

if (gzipOutputStream != null) {

try {

gzipOutputStream.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

return new sun.misc.BASE64Encoder().encode(byteArrayOutputStream.toByteArray());

}

/**

* 解压缩

* @param compressedStr 压缩后的字符串

* @return 解压后的字符串

*/

public static String uncompress(String compressedStr) {

if (compressedStr == null) {

return null;

}

byte[] compressed;

String decompressed=null;

ByteArrayInputStream byteArrayInputStream = null;

GZIPInputStream gzipInputStream = null;

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

try {

compressed = new sun.misc.BASE64Decoder().decodeBuffer(compressedStr);

byteArrayInputStream = new ByteArrayInputStream(compressed);

gzipInputStream = new GZIPInputStream(byteArrayInputStream);

byte[] buffer = new byte[1024];

int offset;

while ((offset = gzipInputStream.read(buffer)) != -1) {

byteArrayOutputStream.write(buffer, 0, offset);

}

decompressed = byteArrayOutputStream.toString();

} catch (IOException e) {

e.printStackTrace();

} finally {

if (gzipInputStream != null) {

try {

gzipInputStream.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if (byteArrayInputStream != null) {

try {

byteArrayInputStream.close();

} catch (IOException e) {

e.printStackTrace();

}

}

try {

byteArrayOutputStream.close();

} catch (IOException e) {

e.printStackTrace();

}

}

return decompressed;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值