package com.bcxin.survey.utils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; /** * @author aluo * String压缩/解压 */ public class StringCompress { /** * 压缩字符串 * * @param str * 压缩的字符串 * @return 压缩后的字符串 */ public static String compress(String str) { if (str == null || str.length() == 0) { return str; } ByteArrayOutputStream out = new ByteArrayOutputStream(); GZIPOutputStream gzip; try { gzip = new GZIPOutputStream(out); gzip.write(str.getBytes()); gzip.close(); return out.toString("ISO-8859-1"); } catch (IOException e) { e.printStackTrace(); } return str; } /** * 解压缩字符串 * * @param str * 解压缩的字符串 * @return 解压后的字符串 */ public static String decompress(String str){ if (str == null || str.length() == 0) { return str; } ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayInputStream in; try { 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(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ""; } public static void main(String[] args) throws IOException { String a = "我哎祖国"; String c = compress(a); System.out.println(decompress(c)); } }