java 压缩多个文件_java实现一次性压缩多个文件到zip中的方法示例
本文實例講述了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?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?
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?sourceFilePaths?=?new?ArrayList();
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+"個文件");
}
總結
以上是生活随笔為你收集整理的java 压缩多个文件_java实现一次性压缩多个文件到zip中的方法示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python中color的用法_pyth
- 下一篇: java super实例_java S