gzip compression solution for Java strings
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;
Compress and decompress a string in zip mode
public class ZipUtil2 {
Compression
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");
}
Decompression
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 () uses the platform default encoding, or it can explicitly specify such as ToString (" gbk")
return out.tostring ();
}
Test method
public static void Main (string[] args) throws IOException {
Test string
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 ("Original length:" +str.length ());
SYSTEM.OUT.PRINTLN ("Compressed:" +ziputil2.compress (str). length ());
System.out.println ("Decompress:" +ziputil2.uncompress (ziputil2.compress (str));
}
}