In recent projects using Java to implement the Zip/unzip XML file functionality, Java comes with the API to facilitate the implementation of file compression and decompression, record the relevant code.
- Zip source file to destination file with source file name
Public void Zip(file src, file dest) {InputStreaminch=NULL; Zipoutputstream zos=NULL;Try{Zos =NewZipoutputstream (NewFileOutputStream (dest)); ZipEntry ze=NewZipEntry (Src.getname ()); Zos.putnextentry (Ze);inch=NewFileInputStream (SRC); Ioutils.copy (inch, Zos); }Catch(IOException e) {Log.error ("fail to zip file:"+ src.getname () +"To:"+ Dest.getname ());ThrowE }finally{if(NULL! = Zos) {Try{zos.closeentry (); }Catch(IOException ex) {}} ioutils.closequietly (inch); ioutils.closequietly (ZOS);}
- Extract all files from the source file zip to the destination folder
Public void UnZip(File file, String OutputFolder) {File folder =NewFile (OutputFolder);if(Folder.exists () && folder.isfile ()) {ThrowIllegalArgumentException ("Not an exists folder"); }//create Output Directory is not exists if(!folder.exists () &&!folder.mkdir ()) {ThrowIllegalstatusexception ("fail to create Dest folder"); } InputStreaminch=NULL; OutputStream out=NULL; ZipFile ZipFile =NewZipFile (file); Enumeration EMU = Zipfile.entries (); while(Emu.hasmoreelements ()) {ZipEntry entry = (zipentry) emu.nextelement ();//Create directory if(Entry.isdirectory ()) {NewFile (OutputFolder + entry.getname ()). Mkdirs ();Continue; }//File copyInputStream is= Zipfile.getinputstream (entry); File File =NewFile (OutputFolder + entry.getname ());//Note: ZipFile read files are randomly read, may read a file, and then read the folder, so you may want to create a directory firstFile parent = File.getparentfile ();if(Parent! =NULL&& (!parent.exists ())) {parent.mkdirs (); } out=NewFileOutputStream (file); ioutils.closequietly (inch); ioutils.closequietly ( out); } }Catch(IOException ex) {Log.error (Ex.getmessage ());ThrowEx }finally{if(NULL! = ZipFile) {Try{Zipfile.close (); }Catch(IOException e) {}} ioutils.closequietly (inch); ioutils.closequietly ( out); } }
The most important thing is that the file is too large, ioutils copy consumes CPU high.
Java Zip/unzip Files Records