java多文件压缩成biz
废话不多说,代码说话
//文件地址
List<String> urls = new ArrayList<>();
//文件名称
List<String> name = new ArrayList<>();
String zipFilePath = "D:/NFC.zip";
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFilePath));
try {
for (int i = 0; i < urls.size(); i++) {
String name = names.get(i);
fileToZip(urls.get(i), zipOut,name );
}
// 压缩完成后,关闭压缩流
zipOut.close();
//拼接下载默认名称并转为ISO-8859-1格式
String fileName = new String(("NFC.zip").getBytes(),"ISO-8859-1");
response.setHeader("Content-Disposition", "attchment;filename="+fileName);
//该流不可以手动关闭,手动关闭下载会出问题,下载完成后会自动关闭
ServletOutputStream outputStream = response.getOutputStream();
FileInputStream inputStream = new FileInputStream(zipFilePath);
// copy方法为文件复制,在这里直接实现了下载效果
IOUtils.copy(inputStream, outputStream);
// 关闭输入流
inputStream.close();
//下载完成之后,删掉这个zip包
File fileTempZip = new File(zipFilePath);
fileTempZip.delete();
// map.put("zip",zipFilePath);
// remoteEpFileService.delZip(map);
} catch (Exception e) {
log.info("er",e);
}
public void fileToZip(String filePath,ZipOutputStream zipOut,String name) throws Exception {
Map<String,Object> map = new HashMap<>();
map.put("url",filePath);
File file = remoteEpFileService.response(map);
InputStream input = new FileInputStream(file);
// InputStream fileInput = urlfile.openStream();
String fileName = name;
// FileInputStream fileInput = new FileInputStream(filePath);
// 缓冲
byte[] bufferArea = new byte[1024 * 10];
BufferedInputStream bufferStream = new BufferedInputStream(input, 1024 * 10);
// 将当前文件作为一个zip实体写入压缩流,fileName代表压缩文件中的文件名称
zipOut.putNextEntry(new ZipEntry(fileName));
int length = 0;
while ((length = bufferStream.read(bufferArea, 0, 1024 * 10)) != -1) {
zipOut.write(bufferArea, 0, length);
}
//关闭流
input.close();
// 需要注意的是缓冲流必须要关闭流,否则输出无效
bufferStream.close();
// 压缩流不必关闭,使用完后再关
}