/**
* @Description: 压缩包
* @Param:
* @return:
* @Author: Chenzb
* @Date: 2022/1/12
*/
private void zipPack(String path,HttpServletResponse response){
// 开始准备压缩
String fileName = "courseData";
String zipFilePath = ZipUtil.zipPack(fileName, path);
try(OutputStream outputStream = response.getOutputStream(); InputStream input = new BufferedInputStream( new FileInputStream(zipFilePath));){
// 设定输出文件头
response.setContentType("application/x-zip-compressed");
response.setCharacterEncoding("utf-8");
String codedfilename = URLEncoder.encode("courseData.zip", "UTF-8");
response.setHeader("Content-Disposition", "attachment;fileName=" + codedfilename);
int read = 0;
byte[] bufs = new byte[1024 * 10];
while ((read = input.read(bufs, 0, 1024 * 10)) != -1) {
outputStream.write(bufs, 0, read);
}
} catch (Exception ex) {
ex.printStackTrace();
}finally {
//删除临时文件
try {
FileUtils.deleteDirectory(new File(path));
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static String zipPack(String fileName, String filePath) {
String yyyymm = DateUtil.yyyymmdd_8().substring(0,6);
//打包下载
File zipFolder = new File(filePath);
if(!zipFolder.exists()){
zipFolder.mkdirs();
}
StringBuffer msg =new StringBuffer("");
String zipFilePath = filePath+File.separator+fileName+yyyymm+".zip";
try {
ZipFile zipFile = new ZipFile(zipFilePath);
ZipParameters parameters = new ZipParameters();
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_FASTEST);
zipFile.addFolder(filePath,parameters);
} catch (ZipException e) {
e.printStackTrace();
msg.append("压缩文件失败;");
}
return zipFilePath;
}
Java 文件压缩 并导出写法 亲测可用
最新推荐文章于 2023-08-28 17:22:09 发布