public void downloadFileList(List<String> pathList, HttpServletResponse response) {
List<String> checkNameList = new ArrayList<>();
// 创建临时文件
File zipFile = null;
FileInputStream fis = null;
BufferedInputStream buff = null;
try {
String urlFileName = URLEncoder.encode("xxx文件包", "UTF-8");
//临时文件名称
zipFile = File.createTempFile("批量下载包临时文件", ".zip");
FileOutputStream fot = new FileOutputStream(zipFile);
// 为任何OutputStream产生校验,第一个参数是制定产生校验和的输出流,第二个参数是指定Checksum的类型 (Adler32(较快)和CRC32两种)
CheckedOutputStream cos = new CheckedOutputStream(fot, new Adler32());
// 用于将数据压缩成Zip文件格式
ZipOutputStream zos = new ZipOutputStream(cos);
for (String paths : pathList) {
String path = PathToolkit.getFileLocationPath() + paths;
File file = new File(path);
//根据文件信息获取输入流。这个看实际的业务目的就是获取当前文件的输入流
InputStream inputStream = new FileInputStream(file);
if (ObjectUtil.isAllEmpty(inputStream)) {
break;
}
// 对于每一个要被存放到压缩包的文件,都必须调用ZipOutputStream对象的putNextEntry()方法,确保压缩包里面文件不同名
//多个文件名称重复时zos.putNextEntry()会报错!! 可以再文件名称后面加编号等操作
String fileName = path.substring(path.lastIndexOf("/") + 1);
if (CollectionUtil.isNotEmpty(checkNameList)) {
if (checkNameList.contains(fileName)) {
long count = checkNameList.stream().filter(t -> t.equals(fileName)).count();
checkNameList.add(fileName);
zos.putNextEntry(new ZipEntry(fileName.substring(0, fileName.lastIndexOf(".")) + "(" + count + ")" + fileName.substring(fileName.lastIndexOf("."))));
} else {
checkNameList.add(fileName);
zos.putNextEntry(new ZipEntry(fileName));
}
} else {
checkNameList.add(fileName);
zos.putNextEntry(new ZipEntry(fileName));
}
// int bytesRead = 0;
// // 向压缩文件中输出数据
// while ((bytesRead = inputStream.read()) != -1) {
// zos.write(bytesRead);
// }
byte[] buffer = new byte[1024];
int n = inputStream.read(buffer);
while (n != -1) {
zos.write(buffer, 0, n);
n = inputStream.read(buffer);
}
inputStream.close();
// 当前文件写完,写入下一个文件
zos.closeEntry();
}
zos.close();
ServletOutputStream os = response.getOutputStream();
response.setHeader("code", "200");
response.setHeader("msg", "DOWNLOADSUCCESS");
response.setHeader("Content-Disposition", "attachment;filename=" + urlFileName + ".zip");
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition,code,msg");
fis = new FileInputStream(zipFile);
buff = new BufferedInputStream(fis);
FileCopyUtils.copy(buff, os);
} catch (Exception e) {
e.printStackTrace();
// throw new BusinessException("批量下载失败");
// 关闭流
} finally {
try {
if (null != fis) {
fis.close();
}
if (null != buff) {
buff.close();
}
} catch (IOException e) {
// log.error( "流关闭异常");
}
// 删除临时文件
if (null != zipFile) {
zipFile.delete();
}
}
}
java 批量打包压缩临时文件下载
最新推荐文章于 2024-03-01 14:58:52 发布