For example, compress the zip file. Mainly through the Zipoutputstream class implementation.
ImportJava.io.*;ImportJava.util.*;Importjava.text.*;Importjava.util.zip.*;//Compress a file//Compress a folder Public classhello{ Public Static voidMain (string[] args)throwsException {Final intBuffer_length = 1024*1024; byte[] buffer =New byte[Buffer_length]; File sourcefile=NewFile ("D:\\asmtools"); File ZipFile=NewFile ("d:\\" +getfilename (Sourcefile.getname ()) + ". Zip"); InputStream is=NULL; Zipoutputstream ZipOut=NewZipoutputstream (NewFileOutputStream (ZipFile)); intLen = 0; file[] Files=Sourcefile.listfiles (); for(File file:files) { is=Newfileinputstream (file); Zipout.putnextentry (NewZipEntry (File.getname ())); while((len= is.read (buffer,0,buffer_length)) >0) {zipout.write (buffer,0, Len); } is.close (); } zipout.close (); } Public Staticstring GetFileName (String fileName) {string retVal; intLastIndex = Filename.lastindexof (".")); if(LastIndex < 0) RetVal=FileName; ElseRetVal= filename.substring (0, LastIndex); returnRetVal; }}
Decompression mainly uses the ZipFile class and the Zipoutputstream class.
Zipoutputstream gets each zipentry in the compressed file, and ZipFile takes the input stream through ZipEntry.
ImportJava.io.*;ImportJava.util.*;Importjava.text.*;Importjava.util.zip.*;//Compress a file//Compress a folder Public classhello{ Public Static voidMain (string[] args)throwsException {Final intBuffer_length = 1024*1024; File Sourcezipfile=NewFile ("D:\\asmtools.zip"); File Unzippedfolder=NewFile ("d:\\" +GetFileName (Sourcezipfile.getname ())); Zipinputstream Zipinput=NewZipinputstream (NewFileInputStream (sourcezipfile)); ZipFile ZipFile=NewZipFile (Sourcezipfile); ZipEntry Tempzipentry=NULL; InputStream is=NULL; OutputStream OS=NULL; byte[] buffer =New byte[Buffer_length]; intbytesreaded = 0; if(!unzippedfolder.exists ()) {Unzippedfolder.mkdir (); } while((Tempzipentry = Zipinput.getnextentry ())! =NULL) { is=Zipfile.getinputstream (tempzipentry); OS=NewFileOutputStream ("d:\\" + unzippedfolder.getname () + "\ \" +tempzipentry.getname ()); System.out.println ("Extracting:" +tempzipentry.getname ()); while((bytesreaded = Is.read (buffer,0,buffer_length)) >0) {os.write (buffer,0, bytesreaded); } is.close (); Os.close (); } zipinput.close (); } Public Staticstring GetFileName (String fileName) {string retVal; intLastIndex = Filename.lastindexof (".")); if(LastIndex < 0) RetVal=FileName; ElseRetVal= filename.substring (0, LastIndex); returnRetVal; }}
Compression and decompression in Java