Java多文件压缩下载
今日在做一个文件下载的需求,记录下如何使用Java制作压缩文件并下载。
在这里有个需求是说需要对内部文件名称做整理,所以我们使用Map来做循环处理
public void downloadZip(HttpServletResponse response) {
Map<String, String> fileList = new HashMap<>();
fileList.put("D:\\test/abc.pdf", "xxxx001.pdf");
fileList.put("D:\\test/downtest.pdf", "yyyy001.pdf");
if (MapUtils.isEmpty(fileList)) {
throw new RuntimeException("No file found");
}
ZipOutputStream zipOutputStream = null;
try {
//设置响应头
response.reset();
response.setContentType("application/octet-stream");
response.setCharacterEncoding("utf-8");
//设置文件名称
response.setHeader("Content-Disposition", "attachment;filename=" + "ShipmentLabels.zip");
zipOutputStream = new ZipOutputStream(response.getOutputStream());
for (Map.Entry<String, String> filePath : fileList.entrySet()) {
File file = new File(filePath.getKey());
FileInputStream fis = new FileInputStream(file);
// 对内部文件重命名
ZipEntry zipEntry = new ZipEntry(filePath.getValue());
zipOutputStream.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipOutputStream.write(bytes, 0, length);
}
zipOutputStream.closeEntry();
fis.close();
}
zipOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
//关闭资源
if (null != zipOutputStream) {
try {
zipOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}