java多文件壓縮成ZIP


 1      /**
 2       * 多個文件壓縮
 3       * @param srcFiles   壓縮前的文件
 4       * @param zipFile    壓縮后的文件
 5       */
 6      public static void zipFiles(File[] srcFiles,  File zipFile) {
 7          // 判斷壓縮后的文件存在不,不存在則創建
 8          if (!zipFile.exists()) {
 9              try {
10                  zipFile.createNewFile();
11              } catch (IOException e) {
12                  e.printStackTrace();
13              }
14          }
15          // 創建 FileOutputStream 對象
16          FileOutputStream fileOutputStream = null;
17          // 創建 ZipOutputStream
18          ZipOutputStream zipOutputStream = null;
19          // 創建 FileInputStream 對象
20          FileInputStream fileInputStream = null;
21   
22          try {
23              // 實例化 FileOutputStream 對象
24              fileOutputStream = new  FileOutputStream(zipFile);
25              // 實例化 ZipOutputStream 對象
26              zipOutputStream = new  ZipOutputStream(fileOutputStream);
27              // 創建 ZipEntry 對象
28              ZipEntry zipEntry = null;
29              // 遍歷源文件數組
30              for (int i = 0; i < srcFiles.length;  i++) {
31                  // 將源文件數組中的當前文件讀入  FileInputStream 流中
32                  fileInputStream = new  FileInputStream(srcFiles[i]);
33                  // 實例化 ZipEntry 對象,源文件數組中的當前文件
34                  zipEntry = new  ZipEntry(srcFiles[i].getName());
35                   zipOutputStream.putNextEntry(zipEntry);
36                  // 該變量記錄每次真正讀的字節個數
37                  int len;
38                  // 定義每次讀取的字節數組
39                  byte[] buffer = new byte[1024];
40                  while ((len =  fileInputStream.read(buffer)) > 0) {
41                      zipOutputStream.write(buffer, 0,  len);
42                  }
43                  fileInputStream.close();
44              }
45              zipOutputStream.closeEntry();
46              zipOutputStream.close();
47              fileOutputStream.close();
48          } catch (IOException e) {
49              e.printStackTrace();
50          }finally{
51              //壓縮完成刪除壓縮前的文件
52              for (File file : srcFiles) {
53                 if(file.exists()){
54                     file.delete();
55                 }
56             }
57          }
58      }

 


免責聲明!

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



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