importjava.io.ByteArrayInputStream;importjava.io.ByteArrayOutputStream;importjava.io.IOException;importjava.nio.ByteBuffer;importjava.util.zip.GZIPInputStream;importjava.util.zip.GZIPOutputStream;importorg.kobjects.base64.Base64;/***@authorJinqi 2014/1/27
* GZIP压缩和解压缩的操作类
**/
public classGzipHelper {/**GZIP压缩
*@paramstr 要压缩的字符串
*@returnGZIP压缩后的字符串
*@throwsIOException*/
public static String compress(String str) throwsIOException {byte[] blockcopy =ByteBuffer
.allocate(4)
.order(java.nio.ByteOrder.LITTLE_ENDIAN)
.putInt(str.length())
.array();
ByteArrayOutputStream os= newByteArrayOutputStream(str.length());
GZIPOutputStream gos= newGZIPOutputStream(os);
gos.write(str.getBytes());
gos.close();
os.close();byte[] compressed = new byte[4 +os.toByteArray().length];
System.arraycopy(blockcopy,0, compressed, 0, 4);
System.arraycopy(os.toByteArray(),0, compressed, 4,
os.toByteArray().length);returnBase64.encode(compressed);
}/**GZIP解压缩
*@paramzipText GZIP压缩过的字符串
*@return解压后的字符串
*@throwsIOException*/
public static String decompress(String zipText) throwsIOException {byte[] compressed =Base64.decode(zipText);if (compressed.length > 4)
{
GZIPInputStream gzipInputStream= newGZIPInputStream(new ByteArrayInputStream(compressed, 4,
compressed.length- 4));
ByteArrayOutputStream baos= newByteArrayOutputStream();for (int value = 0; value != -1;) {
value=gzipInputStream.read();if (value != -1) {
baos.write(value);
}
}
gzipInputStream.close();
baos.close();
String sReturn= new String(baos.toByteArray(), "UTF-8");returnsReturn;
}else{return "";
}
}
}