Java向将指定文件(含文件列表)或者指定路径下目录打包成zip格式

  • 运行环境
  • pom依赖
  • 测试方法
  • 测试效果

运行环境

  • 1、springboot 2.2.x
  • 2、maven 3.5.4

pom依赖

     <!--zip压缩依赖--><dependency><groupId>org.apache.ant</groupId><artifactId>ant</artifactId><version>1.10.7</version></dependency><!--注意当你的项目是web项目时,下面的依赖可以不用添加,因为springboot的web起步依赖中含有这个依赖,若是你的项目希望这个可以使zip压缩成为一个可用的工具类,强烈建议加上--><!--压缩文件回传浏览器的依赖包--><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version><scope>provided</scope></dependency>

用于生成zip的工具类

package com.cloud.docment.zip.utils;import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;/*** @Author: Rao* @DateTime: 2020/5/12 14:33* @Description: 将目标文件或者目录进行zip格式打包的工具类*/
public class ZipGenerateUtils {private ZipGenerateUtils() {}/*** 把文件打成压缩包并保存在本地硬盘** @param srcfiles* @param zipPath*/public static void ZipFiles(List srcfiles, String zipPath) {byte[] buf = new byte[4096];ZipOutputStream out = null;try {// 创建zip输出流out = new ZipOutputStream(new FileOutputStream(zipPath));// 循环将源文件列表添加到zip文件中for (int i = 0; i < srcfiles.size(); i++) {File file = new File((String) srcfiles.get(i));FileInputStream in = new FileInputStream(file);String fileName = file.getName();// 将文件名作为zip的Entry存入zip文件中out.putNextEntry(new ZipEntry(fileName));int len;while ( (len = in.read(buf)) > 0) {out.write(buf, 0, len);}out.closeEntry();in.close();}} catch (IOException e) {e.printStackTrace();} finally {if (null != out) {try {out.close();out = null;} catch (IOException e) {e.printStackTrace();}}}}/*** 把文件列表打成压缩包并输出到客户端浏览器中** @param request* @param response* @param srcFiles* @param downloadZipFileName*/public static void ZipFiles(HttpServletRequest request, HttpServletResponse response, List srcFiles, String downloadZipFileName) {byte[] buf = new byte[4096];try {// Create the ZIP file// ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipPath));ZipOutputStream out = new ZipOutputStream(response.getOutputStream());//--设置成这样可以不用保存在本地,再输出,通过response流输出,直接输出到客户端浏览器中。// Compress the filesif (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {downloadZipFileName = new String(downloadZipFileName.getBytes("GB2312"),"ISO-8859-1");} else {// 对文件名进行编码处理中文问题downloadZipFileName = java.net.URLEncoder.encode(downloadZipFileName, "UTF-8");// 处理中文文件名的问题downloadZipFileName = new String(downloadZipFileName.getBytes("UTF-8"), "GBK");// 处理中文文件名的问题}response.reset(); // 重点突出response.setCharacterEncoding("UTF-8"); // 重点突出response.setContentType("application/x-msdownload");// 不同类型的文件对应不同的MIME类型 // 重点突出// inline在浏览器中直接显示,不提示用户下载// attachment弹出对话框,提示用户进行下载保存本地// 默认为inline方式response.setHeader("Content-Disposition", "attachment;filename=" + downloadZipFileName);for (int i = 0; i < srcFiles.size(); i++) {File file = new File((String) srcFiles.get(i));FileInputStream in = new FileInputStream(file);// Add ZIP entry to output stream.String fileName = file.getName();out.putNextEntry(new ZipEntry(fileName));// Transfer bytes from the file to the ZIP fileint len;while ( (len = in.read(buf)) > 0) {out.write(buf, 0, len);}// Complete the entryout.closeEntry();in.close();}// Complete the ZIP fileout.close();System.out.println("压缩完成.");} catch (IOException e) {e.printStackTrace();}}/*** 把文件目录打成压缩包并输出到客户端浏览器中** @param request* @param response* @param sourcePath* @param downloadZipFileName*/public static void createZip(HttpServletRequest request, HttpServletResponse response, String sourcePath, String downloadZipFileName) {byte[] buf = new byte[4096];FileOutputStream fos = null;ZipOutputStream out = null;try {out = new ZipOutputStream(response.getOutputStream());//--设置成这样可以不用保存在本地,再输出,通过response流输出,直接输出到客户端浏览器中。out.setEncoding("gbk");//此处修改字节码方式。if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {downloadZipFileName = new String(downloadZipFileName.getBytes("GB2312"),"ISO-8859-1");} else {// 对文件名进行编码处理中文问题downloadZipFileName = java.net.URLEncoder.encode(downloadZipFileName, "UTF-8");// 处理中文文件名的问题downloadZipFileName = new String(downloadZipFileName.getBytes("UTF-8"), "GBK");// 处理中文文件名的问题}response.reset(); // 重点突出response.setCharacterEncoding("UTF-8"); // 重点突出response.setContentType("application/x-msdownload");// 不同类型的文件对应不同的MIME类型 // 重点突出// 默认为inline方式response.setHeader("Content-Disposition", "attachment;filename=" + downloadZipFileName);writeZip(new File(sourcePath),"",out);out.flush();out.close();System.out.println("当前目录以及子目录和文件已经压缩完成。。。。");} catch (IOException e) {e.printStackTrace();} finally {if(out != null) {try {out.close();out = null;} catch (IOException e) {e.printStackTrace();}}if(fos != null) {try {fos.close();fos = null;} catch (IOException e) {e.printStackTrace();}}}}/*** 创建zip文件* @param file 文件或者目录* @param parentPath 父路径(默认为"")* @param zos ZipOutputStream*/private static void writeZip(File file, String parentPath, ZipOutputStream zos) {if(file.exists()){if(file.isDirectory()){//处理文件夹parentPath += file.getName() + File.separator;File [] files=file.listFiles();if(files.length != 0) {for(File f:files){writeZip(f, parentPath, zos);}} else {//空目录则创建当前目录try {zos.putNextEntry(new ZipEntry(parentPath));} catch (IOException e) {e.printStackTrace();}}} else {FileInputStream fis=null;try {fis=new FileInputStream(file);ZipEntry ze = new ZipEntry(parentPath + file.getName());zos.putNextEntry(ze);byte [] content=new byte[1024];int len;while((len=fis.read(content))!=-1){zos.write(content,0,len);zos.flush();}} catch (FileNotFoundException e) {System.out.println("创建ZIP文件失败");} catch (IOException e) {System.out.println("创建ZIP文件失败");}finally{try {if(fis!=null){fis.close();}}catch(IOException e){System.out.println("创建ZIP文件失败");}}}}}public static void main(String[] args) {//测试文件列表List srcFiles = new ArrayList();srcFiles.add("D:/工作目录/2020/5月/20200511-12/今日工作需求20200511.txt");srcFiles.add("D:/工作目录/2020/5月/20200511-12/完成情况.txt");ZipFiles(srcFiles, "D:\\工作目录\\2020\\5月\\20200511-12\\cszip.zip");}
}

测试方法

package sc.sccdlg.freemarker.controller;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import sc.sccdlg.freemarker.utils.ZipGenerateUtils;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;/*** @Author: Rao* @DateTime: 2020/5/12 15:09* @Description: 测试验证浏览器下载打包的zip文件*/
@Controller
@RequestMapping("/download")
public class DownloadZipController {@RequestMapping("/zip")public String zipToBrowser(HttpServletRequest request, HttpServletResponse response,@RequestParam List<String> srcFiles, @RequestParam String downloadZipFileName){//获取到浏览器数据,调用工具类生成zip压缩的包返回if(!(srcFiles !=null && downloadZipFileName != null)) {System.out.println("参数不正确!");return null;}ZipGenerateUtils.ZipFiles(request,response,srcFiles,downloadZipFileName);return "";}@RequestMapping("/zip1")public String zipToBrowser2(HttpServletRequest request, HttpServletResponse response,@RequestParam String src, @RequestParam String downloadZipFileName){//获取到浏览器数据,调用工具类生成zip压缩的包返回if(!(src !=null && downloadZipFileName != null)) {System.out.println("参数不正确!");return null;}ZipGenerateUtils.createZip(request,response,src,downloadZipFileName);return "";}
}

测试效果

结合我的项目,演示,效果如下:

打开zip压缩包,如下:


注意: 文件内容验证,由于我这边项目最终需要要压缩的图片,因此因此文档内容暂无验证,望诸君借鉴酌情使用。

Java向将指定文件(含文件列表)或者指定路径下目录打包成zip格式相关推荐

  1. 关于springmvc下服务器文件打包成zip格式下载功能

    关于springmvc下服务器文件打包成zip格式下载功能 2016年09月21日 11:22:14 toxic_guantou 阅读数:5731更多 个人分类: 技术点存储 版权声明:本文为博主原创 ...

  2. python打包zip文件_python 解压文件,合并文件 打包成zip格式文件 生成MD5值

    #!/usr/bin/env python #_*_encoding:utf-8 # 2018/05/29 #augustyang #2.0 ''' 解压文件,合并文件 打包成zip格式文件 生成MD ...

  3. php 生成zip并下载,PHP 实现文件打包成zip格式并下载

    PHP 文件打包并下载 有个这样的需求,将多个文件打包成zip格式并下载到本地 可根据 ZipArchive这个类来实现此功能 我自己也研究了一下,然后把搞出来了 ,经测试绝对好用 话不多说直接上代码 ...

  4. think.class.php下载,PHP_ThinkPHP实现将本地文件打包成zip下载,首先,将FileToZip.class文件放到T - phpStudy...

    ThinkPHP实现将本地文件打包成zip下载 首先,将FileToZip.class文件放到ThinkPHP/Extend/Library/ORG/Util/文件夹中,FileToZip.class ...

  5. Java实现文件批量下载,打包成zip压缩包

       最近在做一个管理系统的项目,需要实现一个功能,就是批量下载文件,并打包成zip压缩包.    前端通过POST请求传来要下载的文件列表,Java代码实现如下: import java.io.Bu ...

  6. java 文件流的处理 文件打包成zip

    1.下载文件到本地 public void download(HttpServletResponse response){String filePath ="";//文件路径Str ...

  7. java 把文件打包成zip_java 文件流的处理 文件打包成zip

    1.下载文件到本地 public void download(HttpServletResponse response){ String filePath ="";//文件路径 S ...

  8. Java将多个文件打包成ZIP并下载

    Java将多个文件打包成ZIP并下载 需求是多个文件需要同时打包成zip压缩文件并下载到本地,首先我需要的是知道下载文件的路径.我有一个专门的sys_file_info表,表中有对应的文件路径.业务表 ...

  9. java 把文件打包成zip文件_java将文件或是文件夹打包压缩成zip格式

    导读热词 下面是编程之家 jb51.cc 通过网络收集整理的代码片段. 编程之家小编现在分享给大家,也给大家做个参考. import java.io.BufferedInputStream; impo ...

最新文章

  1. HTTP 各版本特点与区别
  2. 1亿组图文对,填补中文开源多模态数据集空白!还附带基础模型,来自华为诺亚方舟实验室...
  3. Java mybatis实现mysql批量插入
  4. i love you 浪漫字体复制_2020高考英语全国I、II、III卷语篇来源!欢迎转发交流!...
  5. Windows在当前目录快速打开cmd的方法
  6. ESXI6.5 最新版尝鲜安装图解
  7. numpy基础(part14)--积分
  8. react学习(10)----react数组定义 从0开始 直接加个0下标空
  9. Spring Security整合JWT,实现单点登录,So Easy~!
  10. C语言知识点——函数参数
  11. Flutter 学习与性能优化总结
  12. 网友上海求职指南2007
  13. NLP入门:pyltp的介绍与使用
  14. NLP-知识搭建聊天系统详细教程
  15. cppunit在vs2019上的配置和使用【Win10】【详细】
  16. Err.number错误号和错误说明
  17. shader TileMap html的Canvas绘图 缓动/反弹动作 unity
  18. NCUT 数据库基础 铁路购票系统
  19. Tomcat7 配置 WebSocket
  20. 云原生机制的三个核心思想及其未来之路

热门文章

  1. n平方的求和公式_自然数平方数列和立方数列求和公式
  2. NOIP2016提高组口胡题解
  3. Pandas中pivot的使用
  4. NS版暗黑破坏神3金手指开发教程(17)
  5. 多功能工具箱组合小程序源码+附流量主/云开发的
  6. c#编程基础:装箱与拆箱
  7. 【FXCG】什么是风险容忍度?
  8. 如何解决:FileNotFoundError: 以及[Errno 2]No such file or directory
  9. 云端批量管理服务器平台-旗鱼云梯
  10. 深度学习 图像相似度检测 资料