2019-09-02 13:43:16 4423瀏覽
今天千鋒扣丁學(xué)堂Java培訓(xùn)老師給大家分享一篇關(guān)于java實(shí)現(xiàn)一次性壓縮多個文件到zip中的方法示例,涉及java針對文件批量壓縮相關(guān)的文件判斷、遍歷、壓縮等操作技巧,下面我們一起來看一下吧。
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;
/** * @Title: compress * @Description: TODO * @param filePaths 需要壓縮的文件地址列表(絕對路徑) * @param zipFilePath 需要壓縮到哪個zip文件(無需創(chuàng)建這樣一個zip,只需要指定一個全路徑) * @param keepDirStructure 壓縮后目錄是否保持原目錄結(jié)構(gòu) * @throws IOException * @return int 壓縮成功的文件個數(shù) */ public static int compress(List<String> filePaths, String zipFilePath,Boolean keepDirStructure) throws IOException{ byte[] buf = new byte[1024]; File zipFile = new File(zipFilePath); //zip文件不存在,則創(chuàng)建文件,用于壓縮 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){ //保持目錄結(jié)構(gòu) zos.putNextEntry(new ZipEntry(relativePath)); }else{ //直接放到壓縮包的根目錄 zos.putNextEntry(new ZipEntry(sourceFile.getName())); } //System.out.println("壓縮當(dāng)前文件:"+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; }
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"; //調(diào)用壓縮 int s = compress(sourceFilePaths, zipTempFilePath,false); System.out.println("成功壓縮"+s+"個文件"); }
【關(guān)注微信公眾號獲取更多學(xué)習(xí)資料】 【掃碼進(jìn)入JavaEE/微服務(wù)VIP免費(fèi)公開課】
查看更多關(guān)于“Java開發(fā)資訊”的相關(guān)文章>>