First, brief
Zip is used to compress and decompress files. The classes used are: ZipEntry Zipoutputstream
Second, the specific implementation of the Code
Package Com.joyplus.test;import Java.io.file;import java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.io.inputstream;import Java.util.arraylist;import Java.util.list;import Java.util.zip.zipentry;import Java.util.zip.ZipOutputStream;/** * @author * compress all files and folders in file * Source: Path to File source * dest: Compressed file storage path*/ Public classZipFiletest1 {//get all files in the file source PrivateList<file> Getsourceallfiles (String from) {List<File> filelist=NewArraylist<>(); File FromFile=NewFile ( from); File[] Filearr=Fromfile.listfiles (); for(File file:filearr) {if(File.isfile ()) {filelist.add (file); }Else{ //take the recursive method to get all the files in the path's neutron path Filelist.addall (Getsourceallfiles (File.getpath ())); } } returnfileList; } //get the relative path of the file in the folder to maintain the original structure (you can also create a new structure on demand) PrivateString Getrelname (String from, File F) {String name=NULL; Name=f.getabsolutepath (). Replace ( from+"\\",""); Name=name.replace ("\\","/"); System. out. println ("the file relative path is:"+name); returnname; } //Create a compressed file and store it in a new path Public voidCreatezipfile (String from, String dest) {List<File> Filelist=getsourceallfiles ( from); Zipoutputstream Zout=NULL;//generate a Zip output stream Try{zout=NewZipoutputstream (NewFileOutputStream (NewFile (dest)); //put each file in a zip stream for(File f:filelist) {InputStream is=NewFileInputStream (f); String name =getrelname ( from , f);//Get file relative path Keep file original structure zipentry en =new ZipEntry (New File (from). GetName () + "/" +name);
zipentry ens=new ZipEntry (F.getname ()); This simply compresses the individual files and no longer has the previous structure en.setsize (F.length ()); Zout.putnextentry (en); Zout.setcomment ("Test"); //reading the contents of a file intlen=0; byte[] buffer=New byte[1024x768]; while((len= is. Read (buffer))!=-1) {zout.write (buffer,0, Len); } zout.flush (); is. Close (); } zout.close (); } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }finally{ if(zout!=NULL){ Try{zout.close (); } Catch(IOException e) {e.printstacktrace (); } } } } Public Static voidMain (string[] args) {zipFiletest1 test=NewZipFiletest1 (); Test.createzipfile ("d:\\edi_mulit_download\\5fd0998a07c84d9d924076f64fb726a7","D:\\sumzip\\co.zip"); }}
Java.util.zip Compress package File summary One: Compress files and folders below the file