The recent zip operation, from the Internet to find a processing method, but after the test there are some bugs, the main problem is the declaration of file flow, causing the JVM to occupy the file and not release, specifically to make their own changes issued, has been recorded
ImportJava.io.BufferedInputStream;ImportJava.io.BufferedOutputStream;ImportJava.io.File;ImportJava.io.FileInputStream;Importjava.io.FileNotFoundException;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.util.zip.ZipEntry;ImportJava.util.zip.ZipOutputStream; Public classZippic { Public Final Static classFiletozip {PrivateFiletozip () {}/*** The source files stored in the Sourcefilepath directory are packaged in a zip file with the filename name and stored in the Zipfilepath. * @paramsourcefilepath file path to be compressed *@paramZipfilepath Storage Path after compression *@paramfilename Compressed after file name *@returnFlag*/ Public Static Booleanfiletozip (String sourcefilepath,string zipfilepath,string fileName) {BooleanFlag =false; File sourcefile=NewFile (sourcefilepath);if(sourcefile.exists () = =false) {System.out.println (">>>>>> file directory to be compressed:" + Sourcefilepath + "does not exist. <<<<<< "); Flag=false;returnFlag;} Else { Try{File ZipFile=NewFile (Zipfilepath + "/" + FileName + ". zip"); if(Zipfile.exists ()) {System.out.println (">>>>>>" + Zipfilepath + "directory exists under the name:" + fileName + ". zip" + "packaging files. <<<<<< "); } Else{file[] sourceFiles=sourcefile.listfiles ();if(NULL= = SourceFiles | | Sourcefiles.length < 1) {System.out.println (">>>>>> file directory to be compressed:" + Sourcefilepath + "There is no file, no compression. <<<<<< "); Flag=false;returnFlag;} Else{zipoutputstream Zos=NewZipoutputstream (NewBufferedoutputstream (NewFileOutputStream (ZipFile));//when used to affirm, otherwise prone to problems, remember to open after the close, after open first offbyte[] Bufs =New byte[1024*10];//Buffer Block for(inti=0;i<sourcefiles.length;i++) { //Create a Zip entity and add a zipped packageZipEntry ZipEntry =NewZipEntry (Sourcefiles[i].getname ()); Zos.putnextentry (zipentry);//read the file to be compressed and write it into the compressed packageBufferedinputstream bis =NewBufferedinputstream (NewFileInputStream (Sourcefiles[i]), 1024*10);//when used to affirm, otherwise prone to problems, remember to open after the close, after open first offintRead = 0; while((Read= (Bis.read (bufs, 0, 1024*10)))!! =-1) {zos.write (Bufs,0, read);}if(NULL! = bis) bis.close ();//Close}flag=true;if(NULL! = Zos) zos.close ();//Close}}} Catch(FileNotFoundException e) {e.printstacktrace ();Throw NewRuntimeException (e);} Catch(IOException e) {e.printstacktrace ();Throw NewRuntimeException (e);}} returnflag; }}}
Java zip compression optimized version resolves files that have been consumed after compression cannot be deleted