Source: Java Compression decompression class instance [go]
PackageCom.example.helloworld;ImportJava.io.ByteArrayOutputStream;Importjava.io.IOException;ImportJava.util.zip.Deflater;ImportJava.util.zip.Inflater;/*** zlib Compression tool * *@authorpresent *@version1.0 *@since1.0*/ Public Abstract classUtils {/*** Compression * *@paramdata to be compressed *@returnbyte[] Compressed data*/ Public Static byte[] Compress (byte[] data) { byte[] Output =New byte[0]; Deflater Compresser=NewDeflater (); Compresser.reset (); Compresser.setinput (data); Compresser.finish (); Bytearrayoutputstream Bos=NewBytearrayoutputstream (data.length); Try { byte[] buf =New byte[1024]; while(!compresser.finished ()) { inti =compresser.deflate (BUF); Bos.write (BUF,0, i); } Output=Bos.tobytearray (); } Catch(Exception e) {output=data; E.printstacktrace (); } finally { Try{bos.close (); } Catch(IOException e) {e.printstacktrace (); }} compresser.end (); returnoutput; } /*** Unzip * *@paramdata to be compressed *@returnbyte[] decompressed data*/ Public Static byte[] Decompress (byte[] data) { byte[] Output =New byte[0]; Inflater Decompresser=NewInflater (); Decompresser.reset (); Decompresser.setinput (data); Bytearrayoutputstream o=NewBytearrayoutputstream (data.length); Try { byte[] buf =New byte[1024]; while(!decompresser.finished ()) { inti =decompresser.inflate (BUF); O.write (BUF,0, i); } Output=O.tobytearray (); } Catch(Exception e) {output=data; E.printstacktrace (); } finally { Try{o.close (); } Catch(IOException e) {e.printstacktrace (); }} decompresser.end (); returnoutput; } Public Static voidMain (string[] args) {String inputstr= "[email protected]; [Email protected]; [Email protected] "; System.err.println ("Input string: \ t" +inputstr); byte[] input =inputstr.getbytes (); System.err.println ("Input byte length: \ t" +input.length); byte[] data =utils.compress (input); System.err.println ("Byte length after compression: \ t" +data.length); byte[] Output =utils.decompress (data); System.err.println ("Uncompressed byte length: \ t" +output.length); String Outputstr=NewString (output); System.err.println ("Output string: \ t" +outputstr); }}
Java.util.zip.Deflater Compressed Inflater Decompression instance