In recent projects, you need to unzip the zip archive and then store the extracted content in the specified directory.
The characteristics of the package:
- Use standard ZIP compression format (compression algorithm not explored in depth)
- Package with directory and directory name in Chinese
- Add a password when compressing
Because the java.util.zip.* package that comes with the JRE does not support Chinese and encryption compression, the ZIP4J package is selected.
Here is the extracted implementation code:
1 Public classUnZip {2 Private Final intBuff_size = 4096;3 4 /*5 get the file name and directory name in the zip file6 */7 Public voidgetentrynames (String zipfilepath, string password) {8List<string> entrylist =NewArraylist<string>();9 ZipFile ZF;Ten Try { OneZF =NewZipFile (zipfilepath); AZf.setfilenamecharset ("GBK");//By default UTF8, if the file name in the compressed package is GBK it will appear garbled - if(zf.isencrypted ()) { -Zf.setpassword (password);//set a compressed password the } - for(Object obj:zf.getFileHeaders ()) { -Fileheader Fileheader =(fileheader) obj; -String fileName = Fileheader.getfilename ();//the file name will be with the hierarchy directory information + Entrylist.add (fileName); - } +}Catch(zipexception e) { A e.printstacktrace (); at } - returnentrylist; - } - - /* - unzip the files in the ZIP package to the specified directory in */ - Public voidExtract (String zipfilepath, string password, string destDir) { toInputStream is =NULL; +OutputStream OS =NULL; - ZipFile ZF; the Try { *ZF =NewZipFile (ZipFile); $Zf.setfilenamecharset ("GBK");Panax Notoginseng if(zf.isencrypted ()) { - Zf.setpassword (PASSWORD); the } + A for(Object obj:zf.getFileHeaders ()) { theFileheader Fileheader =(fileheader) obj; +String destfile = DestDir + "/" +fileheader.getfilename (); - if(!Destfile.getparentfile (). exists ()) { $Destfile.getparentfile (). Mkdirs ();//Create a directory $ } -is =Zf.getinputstream (fileheader); -OS =NewFileOutputStream (destfile); the intReadlen =-1; - byte[] Buff =New byte[buff_size];Wuyi while((Readlen = Is.read (buff))! =-1) { theOs.write (Buff, 0, Readlen); - } Wu } -}Catch(Exception e) { About e.printstacktrace (); $}finally{ - //Close Resource - Try{ - if(Is! =NULL){ A is.close (); + } the}Catch(IOException IoE) {} - $ Try{ the if(OS! =NULL){ the os.close (); the } the}Catch(IOException IoE) {} - } in } the}
The above code is not tested and is only used as a pseudo-code reference
Use Java to extract the encrypted Chinese ZIP archive package