Packagecom.rick.utils;ImportJava.io.*;ImportJava.util.zip.GZIPInputStream;ImportJava.util.zip.GZIPOutputStream;/******************************************************** * @Desc: GIZP Tool class * @Author: ZRP * @Date: 2017/11/9 9:31 ****** **************************************************/ Public classGziputil {/*** @Desc: gzip compressed * @Author: ZRP * @Params: [Data] * @Return: byte[] * @Date: 2017/11/9 9:43 */ Public Static byte[] gzip (byte[] data)throwsException {bytearrayoutputstream BOS=NewBytearrayoutputstream (); Gzipoutputstream gzip=NewGzipoutputstream (BOS); Gzip.write (data); Gzip.finish (); Gzip.close (); byte[] ret =Bos.tobytearray (); Bos.close (); returnret; } /*** @Desc: gzip uncompressed * @Author: ZRP * @Params: [Data] * @Return: byte[] * @Date: 2017/11/9 9:47 */ Public Static byte[] Ungzip (byte[] data)throwsexception{Bytearrayinputstream bis=Newbytearrayinputstream (data); Gzipinputstream gzip=NewGzipinputstream (bis); byte[] buf =New byte[1024]; intnum =-1; Bytearrayoutputstream Bos=NewBytearrayoutputstream (); while(num = gzip.read (buf, 0, buf.length))! =-1) {bos.write (buf,0, num); } gzip.close (); Bis.close (); byte[] ret =Bos.tobytearray (); Bos.flush (); Bos.close (); returnret; } /*** Test compression and restore *@paramargs *@throwsException*/ Public Static voidMain (string[] args)throwsexception{//Read FileString Readpath = System.getproperty ("User.dir") + File.separatorchar + "sources" + File.separatorchar + "001.jpg"; File File=NewFile (Readpath); FileInputStream in=Newfileinputstream (file); byte[] data =New byte[In.available ()]; In.read (data); In.close (); System.out.println ("File Original size:" +data.length); //Test Compression byte[] Ret1 =gziputil.gzip (data); System.out.println ("Size after compression:" +ret1.length); byte[] Ret2 =Gziputil.ungzip (RET1); System.out.println ("Size after Restore:" +ret2.length); //Write a fileString Writepath = System.getproperty ("User.dir") + File.separatorchar + "receive" + File.separatorchar + "001.jpg"; FileOutputStream Fos=NewFileOutputStream (Writepath); Fos.write (Ret2); Fos.close (); }}
170814, Java using gzip compressed files, restore files