Java实现zip多个文件分组下载
最近写了个批量导出文件的功能, 客户要求根据业务系统为条件分组导出系统附件
业务场景: 月度、季度、年度统计
条件: 根据不同的条件查出系统相关的附件,每个系统的文件要单独放在一个文件夹
根据系统分组
每个分组的附件
/**
* @param start_time 开始时间
* @param end_time 结束时间
* @param ids 选择数据的id
* @param type 类型
*/
@ApiOperation("分组下载")
@GetMapping("/generateFileGroupDownZip")
public BaseRetBean generateFileGroupDownZip(
@ApiParam(value = "开始时间",required = false) @RequestParam(value = "start_time",required = false)String start_time,
@ApiParam(value = "结束时间",required = false) @RequestParam(value = "end_time",required = false) String end_time,
@ApiParam(value = "主键编号",required = false) @RequestParam(value = "ids",required = false) List<String> ids,
@ApiParam(value = "类型",required = false) @RequestParam(value = "type",required = false) Integer type,
HttpServletRequest req, HttpServletResponse response) throws Exception {
BaseRetBean baseRetBean = new BaseRetBean();
// 获取session数据
GmAppSessionConfig sessionConfig=getSession(req);
// 查询语句
List<GmFileQueryBean> gmFileBeans = workOrderService.generateFileGroupDownZip(start_time, end_time, ids, type, sessionConfig.getDeptid());
// 判断是否为空, 如果为空注解结束
if (gmFileBeans.size()==0) {
baseRetBean.setRet(1);
baseRetBean.setMsg("没有文件");
return baseRetBean;
}
//设置最终输出zip文件的目录+文件名
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
String zipFileName = formatter.format(new Date())+".zip";
// 定义zip输出流
ZipOutputStream zipStream = null;
BufferedInputStream bufferStream = null;
File zipFile = new File(zipFileName);
try{
//构造最终压缩包的输出流
zipStream = new ZipOutputStream(new FileOutputStream(zipFile));
// 通过lambda表达式分组
Map<String, List<GmFileQueryBean>> collect = gmFileBeans.stream().collect(Collectors.groupingBy(GmFileQueryBean::getSys_name));
// 遍历分组
for (Map.Entry<String, List<GmFileQueryBean>> entryUser : collect.entrySet()) {
// 获取分组键
String key = entryUser.getKey();
// 获取分组值
List<GmFileQueryBean> entryUserList = entryUser.getValue();
// 如果分组值不为空则遍历数组
if (entryUserList.size()>0) {
// 遍历分组值列表
for (GmFileQueryBean gmFileQueryBean : entryUserList) {
// 获取base64存储的数据
String base64Str = gmFileQueryBean.getData();
// 获取后缀
String suffix = gmFileQueryBean.getType();
// 数据为空
if (base64Str == null) {
baseRetBean.setRet(0);
baseRetBean.setMsg("文件为空");
return baseRetBean;
}
BASE64Decoder decoder = new BASE64Decoder();
// Base64解码,对字节数组字符串进行Base64解码并生成文件
byte[] byt = decoder.decodeBuffer(base64Str);
for (int a = 0, len = byt.length; a < len; ++a) {
// 调整异常数据
if (byt[a] < 0) {
byt[a] += 256;
}
}
InputStream input = new ByteArrayInputStream(byt);
/**
* 文件和文件夹命名
* 文件:名称 + 后缀 (系统名-公单类型-文件类型-随机号-后缀)
* 文件夹:"\\" + 文件名 + "\\"
* 组合使用: 文件夹 + 文件
*/
ZipEntry zipEntry = new ZipEntry( "\\" + key + "\\" + gmFileQueryBean.getSys_name() + "-" +
gmFileQueryBean.getWork_type_name() + "-" + gmFileQueryBean.getFile_type_name() + "-" + StringUtil.getRandomStr(true, 4) + gmFileQueryBean.getType());
zipStream.putNextEntry(zipEntry);
bufferStream = new BufferedInputStream(input, 1024 * 10);
int read = 0;
byte[] buf = new byte[1024 * 10];
while ((read = bufferStream.read(buf, 0, 1024 * 10)) != -1) {
zipStream.write(buf, 0, read);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭流
try {
if(null != bufferStream) {
bufferStream.close();
}
if(null != zipStream){
zipStream.flush();
zipStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
//判断系统压缩文件是否存在:true-把该压缩文件通过流输出给客户端后删除该压缩文件 false-未处理
if(zipFile.exists()){
// 调用下载方法
groupDownZip(response,zipFileName);
zipFile.delete();
}
baseRetBean.setRet(1);
baseRetBean.setMsg("查询成功");
return baseRetBean;
}
/**
*
* @param response http相应
* @param filename 文件名
*/
private void groupDownZip(HttpServletResponse response, String filename){
if (filename != null) {
FileInputStream inputStream = null;
BufferedInputStream bufferedInputStream = null;
OutputStream outputStream = null;
try {
File file = new File(filename);
if (file.exists()) {
//设置Headers
response.setHeader("Content-Type","application/octet-stream");
//设置下载的文件的名称-该方式已解决中文乱码问题
response.setHeader("Content-Disposition","attachment;filename=" + new String(filename.getBytes(), "utf-8"));
inputStream = new FileInputStream(file);
bufferedInputStream =new BufferedInputStream(inputStream);
outputStream = response.getOutputStream();
byte[] buffer = new byte[1024];
int lenth = 0;
while((lenth = bufferedInputStream.read(buffer)) != -1){
outputStream.write(buffer,0,lenth);
}
}else{
String error = Base64Util.encode("文件内容为空");
}
}catch(IOException ex){
ex.printStackTrace();
}finally {
try{
if(inputStream != null){
inputStream.close();
}
if( bufferedInputStream != null ){
bufferedInputStream.close();
}
if( outputStream != null){
outputStream.flush();
outputStream.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
}
}
本文地址:https://blog.csdn.net/qq_39997045/article/details/109996895