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; /*** Package The file below the folder * into a zip archive * *@authorHWT **/ Public classFiletozip {PrivateFiletozip () {}/*** The source files stored in the Sourcefilepath directory, packaged into the filename name of the zip file, and stored in the Zipfilepath path *@paramSourcefilepath: File path to be compressed *@paramZipfilepath: Store path after compression *@paramFileName: The name of the compressed file *@return */ Public Staticstring Filetozip (String sourcefilepath,string zipfilepath,string fileName) {File sourcefile=NewFile (Sourcefilepath); FileInputStream FIS=NULL; Bufferedinputstream bis=NULL; FileOutputStream Fos=NULL; Zipoutputstream Zos=NULL; //Determine if the source file exists if(!sourcefile.exists ()) {System.out.println ("File directory to be compressed:" +sourcefilepath+ "does not exist."); }Else{ Try{ File zipfile=NewFile (Zipfilepath + "/" + FileName + ". zip");
//Determine if the file will be duplicated after compression if(Zipfile.exists ()) {System.out.println (Zipfilepath+ "Directory already exists with name" + FileName + ". zip" + "file"); }Else{
//Get all files under the source folder 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."); }Else{fos=NewFileOutputStream (ZipFile); Zos=NewZipoutputstream (Newbufferedoutputstream (FOS)); byte[] Bufs =New byte[1024*10]; 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 packageFIS =NewFileInputStream (Sourcefiles[i]); Bis=NewBufferedinputstream (FIS, 1024*10); intRead = 0; while((Read=bis.read (bufs, 0, 1024*10))! =-1) {zos.write (Bufs,0, read); } } } } } Catch(FileNotFoundException e) {e.printstacktrace (); Throw NewRuntimeException (e); } Catch(IOException e) {e.printstacktrace (); Throw NewRuntimeException (e); } finally{ //Close the stream Try { if(NULL!=bis) bis.close (); if(NULL!=Zos) zos.close (); } Catch(IOException e) {e.printstacktrace (); Throw NewRuntimeException (e); } } } returnFileName + ". zip"; } Public Static voidMain (string[] args) {String Sourcefilepath= "D:\\source"; String Zipfilepath= "D:\\targetzip"; String FileName= "Test"; STRING fn=Filetozip.filetozip (Sourcefilepath, Zipfilepath, fileName); System.out.println (fn); } }
java-package files as zip compressed files