package com.gzip; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; // 将一个字符串按照zip方式压缩和解压缩 public class ZipUtil2 { // 压缩 public static String compress(String str) throws IOException { if (str == null || str.length() == 0) { return str; } ByteArrayOutputStream out = new ByteArrayOutputStream(); GZIPOutputStream gzip = new GZIPOutputStream(out); gzip.write(str.getBytes()); gzip.close(); return out.toString("ISO-8859-1"); } // 解压缩 public static String uncompress(String str) throws IOException { if (str == null || str.length() == 0) { return str; } ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayInputStream in = new ByteArrayInputStream(str .getBytes("ISO-8859-1")); GZIPInputStream gunzip = new GZIPInputStream(in); byte[] buffer = new byte[256]; int n; while ((n = gunzip.read(buffer))>= 0) { out.write(buffer, 0, n); } // toString()使用平台默认编码,也可以显式的指定如toString("GBK") return out.toString(); } // 测试方法 public static void main(String[] args) throws IOException { //测试字符串 String str="%5B%7B%22lastUpdateTime%22%3A%222011-10-28+9%3A39%3A41%22%2C%22smsList%22%3A%5B%7B%22liveState%22%3A%221"; System.out.println("原长度:"+str.length()); System.out.println("压缩后:"+ZipUtil2.compress(str).length()); System.out.println("解压缩:"+ZipUtil2.uncompress(ZipUtil2.compress(str))); } }
JAVA字符串的GZIP压缩解压缩
转载本文章为转载内容,我们尊重原作者对文章享有的著作权。如有内容错误或侵权问题,欢迎原作者联系我们进行内容更正或删除文章。
上一篇:mysql配置
下一篇:(转)IHS配置安全漏洞: 支持不推荐使用的 SSL 版本、在降级的旧加密上填充 Oracle、检测到 RC4 密码套件、支持弱 SSL 密码套件、 重构 RSA 导出键(又称为 FREAK)
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
Java-长字符串加密
加密:为你的长字符串提供最高级别的保护!!!
加密算法 JAVA -
Java设置JSON字符串参数编码
本文详细介绍了如何在Java中创建JSON字符串以及在Java中设置JSON字符串参数编码的方法。
json 字符串 JSON Java