Data is sometimes compressed and decompressed during data transmission. In this example, gzipoutputstream/gzipinputstream is used.
1. Use ISO-8859-1 as intermediary code to ensure accurate data restoration
2. When determining the character encoding, You can explicitly specify the encoding in the last sentence of the uncompress method.
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 ziputil {
// 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 ");
}
// Extract
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 default platform encoding, or you can explicitly specify tostring ("GBK ")
Return out. tostring ();
}
// Test Method
Public static void main (string [] ARGs) throws ioexception {
System. Out. println (ziputil. uncompress (ziputil. Compress ("China ")));
}
}
Original article: http://www.blogjava.net/fastunit/archive/2008/04/25/195932.html