java壓縮:一次性壓縮多個文件到zip中

1.需要引入包:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.springframework.util.StringUtils;

 2.代碼

/**
     * @Title: compress
     * @Description: TODO
     * @param filePaths 需要壓縮的文件地址列表(絕對路徑)
     * @param zipFilePath 需要壓縮到哪個zip文件(無需創建這樣一個zip,只需要指定一個全路徑)
     * @param keepDirStructure 壓縮後目錄是否保持原目錄結構
     * @throws IOException    
     * @return int   壓縮成功的文件個數
     */
     public static int compress(List<String> filePaths, String zipFilePath,Boolean keepDirStructure) throws IOException{
         byte[] buf = new byte[1024];
         File zipFile = new File(zipFilePath);
         //zip文件不存在,則創建文件,用於壓縮
         if(!zipFile.exists())
             zipFile.createNewFile();
         int fileCount = 0;//記錄壓縮了幾個文件?
         try {
             ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
             for(int i = 0; i < filePaths.size(); i++){
                 String relativePath = filePaths.get(i);
                 if(StringUtils.isEmpty(relativePath)){
                     continue;
                 }
                 File sourceFile = new File(relativePath);//絕對路徑找到file
                 if(sourceFile == null || !sourceFile.exists()){
                     continue;
                 }
                 
                 FileInputStream fis = new FileInputStream(sourceFile);
                 if(keepDirStructure!=null && keepDirStructure){
                     //保持目錄結構
                     zos.putNextEntry(new ZipEntry(relativePath));
                 }else{
                     //直接放到壓縮包的根目錄
                     zos.putNextEntry(new ZipEntry(sourceFile.getName()));
                 }
                 //System.out.println("壓縮當前文件:"+sourceFile.getName());
                 int len;
                 while((len = fis.read(buf)) > 0){
                     zos.write(buf, 0, len);
                 }
                 zos.closeEntry();
                 fis.close();
                 fileCount++;
             }
             zos.close();
             //System.out.println("壓縮完成");
         } catch (Exception e) {
             e.printStackTrace();
         }
         return fileCount;
     }
     

3.測試

 public static void main(String[] args) throws IOException {
         List<String> sourceFilePaths = new ArrayList<String>();
         sourceFilePaths.add("d:/test/C08065.jpg");
         sourceFilePaths.add("d:/test/新建文件夾/C08984.jpg");
         sourceFilePaths.add("d:/test/找不到我.jpg");//試一個找不到的文件
         //指定打包到哪個zip(絕對路徑)
         String zipTempFilePath = "D:/test/test.zip";
         //調用壓縮
         int s = compress(sourceFilePaths, zipTempFilePath,false);
         System.out.println("成功壓縮"+s+"個文件");
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章