importjava.io.ByteArrayInputStream;importjava.io.ByteArrayOutputStream;importjava.io.IOException;importjava.util.zip.GZIPInputStream;importjava.util.zip.GZIPOutputStream;//将一个字符串按照zip方式压缩和解压缩publicclassZipUtil {//压缩publicstaticString compress(String str)throwsIOException {if(str==null||str.length()==0) {returnstr;
}
ByteArrayOutputStream out=newByteArrayOutputStream();
GZIPOutputStream gzip=newGZIPOutputStream(out);
gzip.write(str.getBytes());
gzip.close();returnout.toString("ISO-8859-1");
}//解压缩publicstaticString uncompress(String str)throwsIOException {if(str==null||str.length()==0) {returnstr;
}
ByteArrayOutputStream out=newByteArrayOutputStream();
ByteArrayInputStream in=newByteArrayInputStream(str
.getBytes("ISO-8859-1"));
GZIPInputStream gunzip=newGZIPInputStream(in);byte[] buffer=newbyte[256];intn;while((n=gunzip.read(buffer))>=0) {
out.write(buffer,0, n);
}//toString()使用平台默认编码,也可以显式的指定如toString("GBK")returnout.toString();
}//测试方法publicstaticvoidmain(String[] args)throwsIOException {
System.out.println(ZipUtil.uncompress(ZipUtil.compress("asdfghjklzxcvbnmqwertyuiop134567890"))); } }