
zip和rar
湖北省翻译大赛-豁然开朗是什么意思
2023年3月20日发(作者:typo)java将⽂件夹和⾥⾯的所有⽂件打包成zip或rar并导出,亲测好⽤
有⼀个项⽬需要将⽂件夹⾥⾯的所有⽂件压缩成zip并导出下载,并且保留原来⽂件夹⾥⾯的所有⽬录结构,找了⼀些资料整理了⼀下。
上代码:
importFileUtils;
importIOUtils;
importHttpServletResponse;
import*;
importURLEncoder;
importSimpleDateFormat;
importDate;
importZipEntry;
importZipOutputStream;
publicclassFileZipUtil{
/**
*将指定路径下的所有⽂件打包zip导出
*@paramresponseHttpServletResponse
*@paramsourceFilePath要打包的路径
*@paramfileName下载时的⽂件名称
*@parampostfix下载时的⽂件后缀.zip/.rar
*/
publicstaticvoidexportZip(HttpServletResponseresponse,StringsourceFilePath,StringfileName,Stringpostfix){
//默认⽂件名以时间戳作为前缀
if(k(fileName)){
SimpleDateFormatsdf=newSimpleDateFormat("yyyyMMddHHmmss");
fileName=(newDate());
}
StringdownloadName=fileName+postfix;
//将⽂件进⾏打包下载
try{
OutputStreamos=putStream();
//接收压缩包字节
byte[]data=createZip(sourceFilePath);
();
racterEncoding("UTF-8");
der("Access-Control-Allow-Origin","*");
der("Access-Control-Expose-Headers","*");
//下载⽂件名乱码问题
der("Content-Disposition","attachment;filename="+(downloadName,"UTF-8"));
//der("Content-disposition","attachment;filename*=utf-8''"+downloadName);
der("Content-Length",""+);
tentType("application/octet-stream;charset=UTF-8");
(data,os);
();
();
}catch(Exceptione){
tackTrace();
}
}
/**
*创建zip⽂件
*@paramsourceFilePath
*@returnbyte[]
*@throwsException
*/
privatestaticbyte[]createZip(StringsourceFilePath)throwsException{
ByteArrayOutputStreamoutputStream=newByteArrayOutputStream();
ZipOutputStreamzip=newZipOutputStream(outputStream);
//将⽬标⽂件打包成zip导出
Filefile=newFile(sourceFilePath);
Filefile=newFile(sourceFilePath);
handlerFile(zip,file,"");
//⽆异常关闭流,它将⽆条件的关闭⼀个可被关闭的对象⽽不抛出任何异常。
uietly(zip);
Array();
}
/**
*打包处理
*@paramzip
*@paramfile
*@paramdir
*@throwsException
*/
privatestaticvoidhandlerFile(ZipOutputStreamzip,Filefile,Stringdir)throwsException{
//如果当前的是⽂件夹,则循环⾥⾯的内容继续处理
if(ctory()){
//得到⽂件列表信息
File[]fileArray=les();
if(fileArray==null){
return;
}
//将⽂件夹添加到下⼀级打包⽬录
tEntry(newZipEntry(dir+"/"));
dir=()==0?"":dir+"/";
//递归将⽂件夹中的⽂件打包
for(Filef:fileArray){
handlerFile(zip,f,dir+e());
}
}else{
//如果当前的是⽂件,打包处理
BufferedInputStreambis=newBufferedInputStream(newFileInputStream(file));
ZipEntryentry=newZipEntry(dir);
tEntry(entry);
(leToByteArray(file));
uietly(bis);
();
ntry();
}
}
}
调⽤⽅法:
/**
*导出
*/
@GetMapping("/export")
@NonLoginAnnotation
@NonSignAnnotation
publicvoidgetExport(@AuthInfoAnnotationAuthInfoauthInfo,HttpServletResponseresponse)throwsException{
Zip(response,"D:Java123","违法建筑治理应⽤场景数据采集","zip");
}
需要⽤到的common-io的jar包:
s
commons-io
1.3.2