java打包多个文件至zip
一、pom依赖
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.10.5</version>
</dependency>
二、实现流程
1.得到要输出文件的字节码数组
2.将读取的字节码文件存入map
3.遍历map存入ZipOutputStream流
4.设置响应文件类型及名称
/**
*
* 下载实现方法
*
*/
public JSONObject zipDownLoad(HttpServletResponse response) {
List<ExcelPropertyIndexModel> allMeetingRoom = excelMapper.getContent();
int i=1;
for (ExcelPropertyIndexModel excelPropertyIndexModel : allMeetingRoom) {
excelPropertyIndexModel.setIndex(i);
i++;
}
i=1;
List<MeetingFileExcel> allMeetingFile = excelMapper.getContent();
for (MeetingFileExcel meetingFileExcel : allMeetingFile) {
meetingFileExcel.setId(i);
i++;
}
i=1;
List<MeetingSummaryExcel> allMeetingSummary = excelMapper.getContent();
for (MeetingSummaryExcel meetingFileExcel : allMeetingSummary) {
meetingFileExcel.setId(i);
i++;
}
//以上为用easyExcel导出excel所需数据,不会的自行百度
try {
HashMap<String, byte[]> map = new HashMap<>();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();//创建内存流
ExcelUtil.writeExcelToByteArrayOutputStream(byteArrayOutputStream,allMeetingRoom,"test01","room",ExcelPropertyIndexModel.class);
map.put("test01.xls",byteArrayOutputStream.toByteArray());//字节码数组存入map
byteArrayOutputStream.reset();//重置内存流
ExcelUtil.writeExcelToByteArrayOutputStream(byteArrayOutputStream,allMeetingFile,"test02","meetFile",MeetingFileExcel.class);
map.put("test02.xls",byteArrayOutputStream.toByteArray());
byteArrayOutputStream.reset();
ExcelUtil.writeExcelToByteArrayOutputStream(byteArrayOutputStream,allMeetingSummary,"test03","summary",MeetingSummaryExcel.class);
map.put("test03.xls",byteArrayOutputStream.toByteArray());
byteArrayOutputStream.close();
//存入压缩包
ServletOutputStream outputStream = response.getOutputStream();
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmm");
response.setHeader("Content-Disposition","attachment;filename=Demo.zip");//设置压缩包响应的类型及名称
ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
for (Map.Entry<String, byte[]> stringEntry : map.entrySet()) {
String key = stringEntry.getKey();/
byte[] value = stringEntry.getValue();
zipOutputStream.putNextEntry(new ZipEntry(key));/设置压缩包内容名称
zipOutputStream.write(value);//设置压缩包字节码文件
}
zipOutputStream.close();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
JSONObject object = new JSONObject();
object.put("code",200);
object.put("msg","打包成功");
return object;
}