话不多说直接上代码

文件拷贝,压缩多个文件到指定位置,压缩文件夹及以下子集,web段文件下载的工具类
public class DownFileUtil {/*** @description:  压缩文件夹* @param: [zipFilePath  需要压缩到的位置, inputFile 需要压缩文件夹]* @return: void* @author chenfeng/* @date: 2021/8/16 15:35*/public static void zip(String zipFilePath, File inputFile) throws Exception {ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFilePath));zip(out, inputFile, "");out.close();}public static void zip(ZipOutputStream out, File f, String base) throws Exception {if (f.isDirectory()) {File[] fl = f.listFiles();out.putNextEntry(new ZipEntry(base + "/"));base = base.length() == 0 ? "" : base + "/";for (int i = 0; i < fl.length; i++) {zip(out, fl[i], base + fl[i].getName());//循环添加层级关系}} else {out.putNextEntry(new ZipEntry(base));FileInputStream in = new FileInputStream(f);BufferedInputStream stream = new BufferedInputStream(in);int b;//System.out.println(base);art_kcust_cult_and_managewhile ((b = stream.read()) != -1) {out.write(b);}in.close();stream.close();}}/*** @description:  将多个文件压缩到指定位置* @param: [files 文件集合, outputStream]* @return: void* @author chenfeng* @date: 2021/8/16 15:39*/public static void compressZip(List<File> files, OutputStream outputStream) {ZipOutputStream zipOutStream = null;try {//-- 包装成ZIP格式输出流zipOutStream = new ZipOutputStream(new BufferedOutputStream(outputStream));// -- 设置压缩方法zipOutStream.setMethod(ZipOutputStream.DEFLATED);//-- 将多文件循环写入压缩包for (int i = 0; i < files.size(); i++) {File file = files.get(i);FileInputStream filenputStream = new FileInputStream(file);BufferedInputStream bufferedInputStream = new BufferedInputStream(filenputStream);byte[] data = new byte[(int) file.length()];bufferedInputStream.read(data);//-- 添加ZipEntry,并ZipEntry中写入文件流,这里,加上i是防止要下载的文件有重名的导致下载失败zipOutStream.putNextEntry(new ZipEntry( file.getName()));zipOutStream.write(data);filenputStream.close();bufferedInputStream.close();zipOutStream.closeEntry();}} catch (IOException e) {System.out.println(e);}  finally {try {if (Objects.nonNull(zipOutStream)) {zipOutStream.flush();zipOutStream.close();}if (Objects.nonNull(outputStream)) {outputStream.close();}} catch (IOException e) {System.out.println(e);}}}/*** @description: 文件下载* @param: [response , FilePath  文件路径, downloadName  响应web的文件名]* @return: void* @author chenfeng* @date: 2021/8/16 15:30*/public static void downloadFile(HttpServletResponse response, String FilePath, String downloadName) throws IOException {//文件下载OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());File zipFile = new File(FilePath);response.reset();response.setContentType("application/force-download");String fileName = URLEncoder.encode(downloadName, "UTF-8");response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);response.addHeader("Content-Length", "" + zipFile.length());if (!zipFile.exists()) {//-- 需要下载压塑包文件不存在return ;}BufferedInputStream bis=null;try {bis = new BufferedInputStream(new FileInputStream(zipFile));byte[] data = new byte[(int) zipFile.length()];bis.read(data);outputStream.write(data);outputStream.flush();} catch (IOException  e) {System.out.println(e);} finally {try {if (Objects.nonNull(bis)) {bis.close();}if (Objects.nonNull(outputStream)) {outputStream.close();}} catch (IOException e) {System.out.println(e);}}}//文件删除public static boolean delFile(File file) {if (!file.exists()) {return false;}if (file.isDirectory()) {File[] files = file.listFiles();for (File f : files) {delFile(f);}}return file.delete();}
}
//过滤掉文件,只查询文件夹
public class DirectoryFiler implements FileFilter {@Overridepublic boolean accept(File pathname) {if(pathname.isDirectory())return true;return false;}
}//只查询文件
public class FilesFilter implements FileFilter {@Overridepublic boolean accept(File pathname) {if(pathname.isFile())return true;return false;}
}

```Controller层
/** @author chenfeng* @version 1.0* @className: DownController* @date 2021/8/13 9:42*/@RestController
@RequestMapping("/down")
public class DownController {@Autowiredprivate IReportsService reportsService;@Autowiredprivate TableAnnexesBiz tableAnnexesBiz;@Autowiredprivate IPreSettlementDetailedService preSettlementDetailedService;@AutowiredFileUtil fileUtil;@Value("${yiming.file.exportDirectory}")private String export;@GetMapping("/downMoney")public void downMoney(HttpServletResponse response,@RequestParam String number,@RequestParam String type) throws Throwable {String pathName = tableAnnexesBiz.getRootPath();String newFilePath=fileUtil.getStaticPath()+File.separator+export+File.separator+"zip";String newPath="";//批次文件夹File newFile = new File(newFilePath);if(!newFile.exists()){newFile.mkdirs();}File[] listFiles = newFile.listFiles(new FilesFilter());//先查询压缩路径下存在的文件String zipName=number+type+".zip";if (listFiles!=null&&listFiles.length>0) {for (File listFile : listFiles) {if(zipName.equals(listFile.getName())){DownFileUtil.downloadFile(response,newFilePath+File.separator+zipName,zipName);return;}}}//添加过滤器,获取文件夹下所以文件夹File file = new File(pathName);//父级目录File[] fileNames = file.listFiles(new DirectoryFiler());//批次Boolean flag=true;if(fileNames!=null&&fileNames.length>0&&"0".equals(type)){for (File fileName : fileNames) {if(number.equals(fileName.getName())){//根据批次号获取File[] filebatch = fileName.listFiles(new DirectoryFiler());//获取分类文件夹newPath=newFilePath+"\\"+fileName.getName();//新路径文件夹File fileBatchDirectory = new File(newPath);fileBatchDirectory.mkdirs();/* //复制报表文件File[] files = fileName.listFiles(new FilesFilter());if(files!=null){for (File oldFile : files) {DownFileUtil.copyFile(oldFile,new File(newPath+"\\"+oldFile.getName()));}}*/if (filebatch!=null&&filebatch.length>0) {for (File filebatch1 : filebatch) {PreSettlementDetailed one = preSettlementDetailedService.getById(filebatch1.getName());String fjFile=newPath + File.separator + one.getServiceItemsName()+"附件";File file2 = new File(fjFile);if(!file2.exists()){file2.mkdirs();}//获取存放附加压缩路径File[] fileClass= filebatch1.listFiles(new FilesFilter());File[] files = filebatch1.listFiles(new DirectoryFiler());if (fileClass.length>0) {//下一级就是文件的情况List<File> appendix = Arrays.asList(fileClass);for (File oldFile : appendix) {DownFileUtil.copyFile(oldFile,new File(fjFile+File.separator+oldFile.getName()));}}if (files!=null&&files.length>0) {//还有一层文件夹for (File file1 : files) {File[] files1 = file1.listFiles(new FilesFilter());if (files1!=null&&files1.length>0) {//下一级就是文件的情况List<File> appendix = Arrays.asList(files1);for (File oldFile : appendix) {DownFileUtil.copyFile(oldFile,new File(fjFile+File.separator+oldFile.getName()));}}}}}}down(number,newPath,response,type);flag=false;break;}}if(flag){newPath=newFilePath+"\\"+number;//新路径文件夹File fileBatchDirectory = new File(newPath);fileBatchDirectory.mkdirs();down(number,newPath,response,type);}}//只需要下载报表if("1".equals(type)){newPath=newFilePath+"\\"+number;//新路径文件夹File fileBatchDirectory = new File(newPath);fileBatchDirectory.mkdirs();down(number,newPath,response,type);}}public  void  down(String number,String newPath,HttpServletResponse response,String type) throws Exception{Map<String, Object> map = new HashMap<>();map.put("batchId",number);reportsService.exportReport(newPath+"\\",map);DownFileUtil.zip(newPath+type+".zip", new File(newPath));//压缩整个文件夹String downloadName=number+type+".zip";//下载文件名DownFileUtil.downloadFile(response,newPath+type+".zip",downloadName);File newBatchFile = new File(newPath); //新路径下的文件夹DownFileUtil.delFile(newBatchFile);/*  //删除文件夹以及文件File[] files = newBatchFile.listFiles(new FilesFilter());for (File file1 : files) {file1.delete();}if(newBatchFile.exists()){newBatchFile.delete();}*/}}

最后出现新路径zip 再下面存放压缩的文件,下次下载的时候就首先查询压缩文件里面有没有

实现web多层级文件压缩并下载相关推荐

  1. javaweb通过接口来实现多个文件压缩和下载(包括单文件下载,多文件批量下载)

      程序员在做web等项目的时候,往往都需要添加文件上传.下载.删除的功能,有时是单文件,有时多文件批量 操作,而这些功能的代码程序员可以自己收藏起来当成工具使用,这样,程序员在进行程序设计的时候就会 ...

  2. Java将一个文件夹下多个文件压缩并下载(工作案例)

    Java将一个文件下多个文件压缩并下载,文件夹目录如下: 每个文件下都有文件,要求实现将文件夹"A2023001_检查"压缩成"A2023001.zip",如下 ...

  3. springboot单文件下载和多文件压缩zip下载

    微信搜索:"二十同学" 公众号,欢迎关注一条不一样的成长之路 单文件下载 //下载单个文件 public void downloadFile(HttpServletResponse ...

  4. java文件下载接口_javaweb通过接口来实现多个文件压缩和下载(包括单文件下载,多文件批量下载)...

    @RequestMapping("/uploads")public void recursion(String root, Vector vecFile,HttpServletRe ...

  5. Java把文件压缩然后下载

    一边压缩一边下载,前端写法可以参考Java通过流下载文件以及相关优化 response.setContentType("application/octet-stream");res ...

  6. 继上一篇博客--javaweb通过接口来实现多个文件压缩和下载(包括单文件下载,多文件批量下载)

    通过动态分配地址来提升javaweb文件下载接口的其兼容性和可扩展性: (上篇博文地址:https://blog.csdn.net/weixin_37766296/article/details/80 ...

  7. Java 文件压缩及下载

    /*** @author zshuo* @date 2019/3/16*/ public class FileUtil {/*** 把文件打成压缩包并保存在本地硬盘*/public static vo ...

  8. Android与Asp.Net Web服务器的文件上传下载BUG汇总[更新]

    遇到的问题: 1.java.io.IOException: open failed: EINVAL (Invalid argument)异常,在模拟器中的sd卡创建文件夹和文件时报错 出错原因可能是: ...

  9. SpringMVC整合fastdfs-client-java实现web文件上传下载

    为什么80%的码农都做不了架构师?>>>    版权声明:本文为博主原创文章,转载请标明出处(http://blog.csdn.net/wlwlwlwl015)Thanks. 目录( ...

最新文章

  1. 利用jQuery实现用户名片小动画
  2. python随机生成字符串_Python 2.6中的随机字符串(可以吗?)
  3. linux设备驱动程序调试方法,Linux设备驱动程序学习(2)-调试技术
  4. java自动生成类_自动生成优化的Java类专业知识
  5. 面试问题:Spring中Bean 的生命周期
  6. ADO.NET学习笔记--索引Index
  7. linux的mongo主从异常,解决Linux系统下MongoDB数据库异常退出的问题
  8. Java如何使用JDOM解析XML呢?
  9. 关于Echarts官网httpsecharts.apache.org打不开的解决方案
  10. 打印服务器后台程序没有运行,win10遇到“打印后台程序服务没有运行”的解决方法...
  11. SLT学习(二)——容器
  12. Gensim介绍以及实践
  13. 将DXSDK的帮助文档加入到VS6的MSDN中
  14. 复制链接到safari浏览器打开_通过 URL 协议实现从 Safari 等浏览器中跳转打开你的 app...
  15. 春节荐书 | 2019年我读过的十本好书
  16. C语言中关于位域的介绍
  17. Nature封面论文撤稿闹大了,认定首个室温超导体数据存疑!领域大佬尝试复现6次全失败,9位作者集体抗议无效...
  18. 【vcpkg】下载软件包时的提示
  19. 2021-05-16刷题
  20. 利哥测试第2说--软件测试笔试题库

热门文章

  1. checkbox多选框,radio单选框
  2. Python离线安装包教程
  3. 【MATLAB】Linux下的matlab的安装
  4. linux 触摸屏驱动中断下半部实现-工作队列
  5. oracle 19c打补丁,Oracle 19c RAC打补丁过程避坑指南
  6. Windows 无法访问指定设备、路径或文件。你可能没有适当的权限访问该项目。
  7. 【云原生之Docker实战】使用Docker部署Rap2开源接口管理工具
  8. VFP视频教程计划启动
  9. [全网首发]一款好看的个人主页源码
  10. 日撸力扣三道题---Day3---数组算法+二分查找