使用JAVA解壓加密的中文ZIP壓縮包


近來項目中需要對ZIP壓縮包解壓,然后將解壓后的內容存放到指定的目錄下。

該壓縮包的特性:

  1. 使用標准的zip壓縮格式(壓縮算法沒有深入探究)
  2. 壓縮包中帶有目錄並且目錄名稱是中文
  3. 壓縮時加了密碼

因為jre中自帶的java.util.zip.*包不支持中文及加密壓縮,所以選擇使用zip4j包。

下面是解壓的實現代碼:

 1 public class UnZip {
 2     private final int BUFF_SIZE = 4096;
 3     
 4     /*
 5     獲取ZIP文件中的文件名和目錄名
 6     */
 7     public void getEntryNames(String zipFilePath, String password){
 8         List<String> entryList = new ArrayList<String>();
 9         ZipFile zf;
10         try {
11             zf = new ZipFile(zipFilePath);
12             zf.setFileNameCharset("gbk");//默認UTF8,如果壓縮包中的文件名是GBK會出現亂碼
13             if(zf.isEncrypted()){
14                 zf.setPassword(password);//設置壓縮密碼
15             }
16             for(Object obj : zf.getFileHeaders()){
17                 FileHeader fileHeader = (FileHeader)obj;
18                 String fileName = fileHeader.getFileName();//文件名會帶上層級目錄信息
19                 entryList.add(fileName);
20             }
21         } catch (ZipException e) {
22             e.printStackTrace();
23         }
24         return entryList;
25     }
26 
27     /*
28     將ZIP包中的文件解壓到指定目錄
29     */
30     public void extract(String zipFilePath, String password, String destDir){
31         InputStream is = null;
32         OutputStream os = null;
33         ZipFile zf;
34         try {
35             zf = new ZipFile(zipFile);
36             zf.setFileNameCharset("gbk");
37             if(zf.isEncrypted()){
38                 zf.setPassword(PASSWORD);
39             }
40             
41             for(Object obj : zf.getFileHeaders()){
42                 FileHeader fileHeader = (FileHeader)obj;
43                 String destFile = destDir + "/" + fileHeader.getFileName();
44                 if(!destFile.getParentFile().exists()){
45                     destFile.getParentFile().mkdirs();//創建目錄
46                 }
47                 is = zf.getInputStream(fileHeader);
48                 os = new FileOutputStream(destFile);
49                 int readLen = -1;
50                 byte[] buff = new byte[BUFF_SIZE];
51                 while ((readLen = is.read(buff)) != -1) {
52                     os.write(buff, 0, readLen);
53                 }
54             }
55         }catch(Exception e){
56             e.printStackTrace();
57         }finally{
58             //關閉資源
59             try{
60                 if(is != null){
61                     is.close();
62                 }
63             }catch(IOException ioe){}
64             
65             try{
66                 if(os != null){
67                     os.close();
68                 }
69             }catch(IOException ioe){}
70         }
71     }
72 }

 

以上代碼未經測試,僅作為偽代碼參考


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM