將多個檔案壓縮到一個檔

  /**
   * 壓縮檔案
   * @param filePathList 檔案列表
   * @param zipDest 壓縮檔資料夾
   * @return 壓縮檔路徑
   * @throws IOException
   */
public String batchDownLoadFile(List<String> filePathList, String zipDest) throws IOException {

    File zipFile = new File(zipDest, System.nanoTime() + ".zip");

    FileOutputStream fos = new FileOutputStream(zipFile);
    ZipOutputStream zos = new ZipOutputStream(fos);
    FileInputStream fis = null;
    
    Set<String> filePathSet = new HashSet<>(filePathList);
    
    try {
      for(String filePath: filePathSet) {
        fis = new FileInputStream(filePath);
        File file = new File(filePath);
        
        zos.putNextEntry(new ZipEntry(file.getName()));
      
        int tmp = 0;
        while((tmp = fis.read()) != -1) {
          zos.write(tmp);
        }
        zos.flush();
        fis.close();
        zos.closeEntry();
      } 
    }finally {
      zos.close();
      fos.close();
    }

    return zipFile.getPath();
  }

    咪卡恰比 發表在 痞客邦 留言(0) 人氣()