Java string compression and decompression

Source: Internet
Author: User
Tags uncompress
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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.