java壓縮多個文件
阿新 • • 發佈:2019-02-20
pre comm util trac ack ring isempty tac next
首先創建一個工具類,定義好接口,這裏的參數
1:fileList:多個文件的path+name
2: zipFileName:壓縮後的文件名
下面是代碼,註釋已經很詳細了
public class ZIPUtil { public static String createZipFile(ArrayList<String> fileList, String zipFileName) { if(fileList == null || fileList.size() == 0 || CommonUtil.isEmpty(zipFileName)){ return null; } //構建壓縮文件File File zipFile = new File(zipFileName); //初期化ZIP流 ZipOutputStream out = null; try{ //構建ZIP流對象 out = new ZipOutputStream(new FileOutputStream(zipFile)); //循環處理傳過來的集合 for(int i = 0; i < fileList.size(); i++){ //獲取目標文件 File inFile = new File(fileList.get(i)); if(inFile.exists()){ //定義ZipEntry對象 ZipEntry entry = new ZipEntry(inFile.getName()); //賦予ZIP流對象屬性 out.putNextEntry(entry); int len = 0 ; //緩沖 byte[] buffer = new byte[1024]; //構建FileInputStream流對象 FileInputStream fis; fis = new FileInputStream(inFile); while ((len = fis.read(buffer)) > 0) { out.write(buffer, 0, len); out.flush(); } //關閉closeEntry out.closeEntry(); //關閉FileInputStream fis.close(); } } }catch (IOException e) { e.printStackTrace(); }finally{ try { //最後關閉ZIP流 out.close(); } catch (IOException e) { e.printStackTrace(); } } return zipFileName; } }
來源:https://segmentfault.com/a/1190000018211825
java壓縮多個文件