文件压缩下载

package com.ruoyi.utils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/*** @Auther: ZHANG PU* @Date: 2022/6/7 18:01* @Description:*/
public class ZipUtils {private static final int BUFFER_SIZE = 2 * 1024;/*** 压缩成ZIP 方法1** @param srcDir           压缩文件夹路径* @param out              压缩文件输出流* @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;*                         false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)* @throws RuntimeException 压缩失败会抛出运行时异常*/public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure) throws RuntimeException {long start = System.currentTimeMillis();ZipOutputStream zos = null;try {zos = new ZipOutputStream(out);File sourceFile = new File(srcDir);compress(sourceFile, zos, sourceFile.getName(), KeepDirStructure);long end = System.currentTimeMillis();System.out.println("压缩完成,耗时:" + (end - start) + " ms");} catch (Exception e) {throw new RuntimeException("zip error from ZipUtils", e);} finally {if (zos != null) {try {zos.close();} catch (IOException e) {e.printStackTrace();}}}}/*** 压缩成ZIP 方法2** @param srcFiles 需要压缩的文件列表* @param out      压缩文件输出流* @throws RuntimeException 压缩失败会抛出运行时异常*/public static void toZip(List<File> srcFiles, OutputStream out) throws RuntimeException {long start = System.currentTimeMillis();ZipOutputStream zos = null;try {zos = new ZipOutputStream(out);for (File srcFile : srcFiles) {byte[] buf = new byte[BUFFER_SIZE];zos.putNextEntry(new ZipEntry(srcFile.getName()));int len;FileInputStream in = new FileInputStream(srcFile);while ((len = in.read(buf)) != -1){zos.write(buf, 0, len);}zos.closeEntry();in.close();}long end = System.currentTimeMillis();} catch (Exception e) {throw new RuntimeException("zip error from ZipUtils", e);} finally {if (zos != null) {try {zos.close();} catch (IOException e) {e.printStackTrace();}}}}/*** 递归压缩方法** @param sourceFile       源文件* @param zos              zip输出流* @param name             压缩后的名称* @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;*                         false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)* @throws Exception*/private static void compress(File sourceFile, ZipOutputStream zos, String name, boolean KeepDirStructure) throws Exception {byte[] buf = new byte[BUFFER_SIZE];if (sourceFile.isFile()) {// 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字zos.putNextEntry(new ZipEntry(name));// copy文件到zip输出流中int len;FileInputStream in = new FileInputStream(sourceFile);while ((len = in.read(buf)) != -1){zos.write(buf, 0, len);}zos.closeEntry();in.close();} else {File[] listFiles = sourceFile.listFiles();if (listFiles == null || listFiles.length == 0){// 需要保留原来的文件结构时,需要对空文件夹进行处理if (KeepDirStructure){// 空文件夹的处理zos.putNextEntry(new ZipEntry(name + "/"));// 没有文件,不需要文件的copyzos.closeEntry();}} else {for (File file : listFiles){// 判断是否需要保留原来的文件结构if (KeepDirStructure){// 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,// 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了compress(file, zos, name + "/" + file.getName(), KeepDirStructure);} else {compress(file, zos, file.getName(), KeepDirStructure);}}}}}public static void main(String[] args) throws Exception {FileOutputStream fos1 = new FileOutputStream(new File("c:/mytest01.zip"));ZipUtils.toZip("D:/log", fos1, true);List<File> fileList = new ArrayList<>();fileList.add(new File("D:/Java/jdk1.7.0_45_64bit/bin/jar.exe"));fileList.add(new File("D:/Java/jdk1.7.0_45_64bit/bin/java.exe"));FileOutputStream fos2 = new FileOutputStream(new File("c:/mytest02.zip"));ZipUtils.toZip(fileList, fos2);}/*** 压缩图片下载* @param request* @param response* @param fileUrl* @throws Exception*/public static void downImageZip(HttpServletRequest request, HttpServletResponse response,List<String> fileUrl) throws Exception{//创建临时文件夹String rootPath = request.getSession().getServletContext().getRealPath("/");File temDir = new File(rootPath + "/" + UUID.randomUUID().toString().replaceAll("-", ""));if(!temDir.exists()){temDir.mkdirs();}//生成需要下载的文件,存放在临时文件夹内for (String url : fileUrl){if(StringUtils.isNotBlank(url)){String fileName = url.substring(url.lastIndexOf("/") + 1, url.length());byte[] btImg = UrlConverStreamUtils.getImageFromNetByUrl(url);FileOutputStream fops = new FileOutputStream(temDir.getPath()+"/"+fileName);fops.write(btImg);fops.flush();fops.close();}}//设置response的headerresponse.setContentType("application/zip");response.setHeader("Content-Disposition", "attachment; filename="+ DateUtils.dateTime(new Date()) +".zip");// 下载zip压缩包,不需要保留目录结构ZipUtils.toZip(temDir.getPath(), response.getOutputStream(),false);//删除临时文件和文件夹File[] listFiles = temDir.listFiles();for (int i = 0; i < listFiles.length; i++){listFiles[i].delete();}temDir.delete();}
}

java实现文件压缩下载相关推荐

  1. Java多文件压缩下载解决方案

    Java多文件压缩下载解决方案 需求: 会员运营平台经过改版后页面增加了许多全部下载链接,上周上线比较仓促,全部下载是一个直接下载ZIP压缩文件的链接,每个ZIP压缩文件都是由公司运营人员将页面需要下 ...

  2. java实现文件压缩下载----压缩下载zip

    文件压缩下载 Controller层: /** *文件压缩下载 *billname:文件名 *filename:文件存放路径 */ public void downloadsource(HttpSer ...

  3. java实现下载压缩文件_java实现文件压缩下载----压缩下载zip

    文件压缩下载 Controller层: /** *文件压缩下载 *billname:文件名 *filename:文件存放路径 */ public void downloadsource(HttpSer ...

  4. 【java】 文件批量下载并压缩为zip压缩包

    [java] 文件批量下载并压缩为zip压缩包 java常用的压缩技术 java中常见实现压缩与解压 业务场景 代码实现 注意点 java常用的压缩技术 常见的压缩格式有很多种,例如:zip.rar. ...

  5. 批量文件压缩下载(zip)

    ps:工作之余仅留备份用,未全面完善,请按需取用 一.主要关注两点:1.找到文件并压缩:2.通过文件输出流响应前端 @RestController @RequestMapping("/fil ...

  6. php excel模板导出、openoffice excel转pdf、多文件压缩下载

    最近两周都在弄关于excel模板导出.excel转pdf.多文件压缩下载.弄得头都大了,接下来说说实现的方法吧. 我用的是laravel5.1的框架,读取模板生成excel,并且插入图片,直接上代码 ...

  7. java mp3文件压缩_java实现文件压缩

    java实现文件压缩:主要是流与流之间的传递 代码如下: package com.cst.klocwork.service.zip; import java.io.File; import java. ...

  8. java实现文件压缩与解压

    用java实现文件的压缩与解压是很常见的功能. 我最爱上代码: 1 import java.io.File; 2 import java.util.ArrayList; 3 import java.u ...

  9. Java实现文件压缩与解压[zip格式,gzip格式]

    原文:http://www.cnblogs.com/visec479/p/4112881.html#3069573 Java实现ZIP的解压与压缩功能基本都是使用了Java的多肽和递归技术,可以对单个 ...

最新文章

  1. powerdesigner 同步mysql 报错_PowerDesigner实用技巧小结 及 导出word,想字段顺序跟模型中一致,如何设置...
  2. 计算几个变量之间的相关系数,计算协方差矩阵时:TypeError: cannot perform reduce with flexible type
  3. linux yum install libsdl-dev 报错:No package libsdl-dev available 解决方法
  4. PowerDesigner15官方正式版+注册补丁
  5. 数据库-数据库的备份与恢复
  6. Gradle构建中:No cached version available for offline mode解决方案
  7. 一个Demo让你掌握Android所有控件
  8. 【转】c# 协变与抗变
  9. jQuery遍历,数组,集合
  10. Dungeon Master(信息学奥赛一本通-T1248)
  11. ssm项目直接加html文件,如何把ssm项目和vue项目部署在云服务器(上)
  12. 警告:MySQL-server-5.6.26-1.el7.x86_64.rpm: 头V3 DSA/SHA1 Signature, 密钥 ID 5072e1f5: NOKEY
  13. 基于vue与element ui的vue-cron插件的使用及将定时任务cron表达式解析成中文
  14. signature=0142b13a38da3ce7be8fce0d56b678af,授权系统
  15. 企业网站制作中CMS系统的作用及现状
  16. Python入门笔记(第五期——序列的应用2)
  17. 直角坐标系与极坐标系了解与转换
  18. 应聘华为的朋友小心了,应聘华为的悲惨遭遇!
  19. Asciidoctor基础语法
  20. R语言 第三方软件包的下载及安装

热门文章

  1. 2017年数据可视化的七大趋势!
  2. 信捷总线Xnet-速度模式使用总结
  3. 煤炭行业信息化 生产领先与管理滞后并存
  4. 江西计算机职业学校排名2015,2015江西专科学校排名及排行榜
  5. SSM+Maven+Mysql+BootStrap+Echarts网上银行交易系统前台系统
  6. 道德是商業和國力的基礎-逃票
  7. mysql 更新子表_mysql 在update中实现子查询的方式
  8. Struts2中关于There is no Action mapped for namespace / and action name的错误解决
  9. 新概念二册 Lesson 41 Do you call that a hat?你把那个叫帽子吗?(need 用法)
  10. 2022年最新广东建筑安全员模拟题库及答案