第一句子网 - 唯美句子、句子迷、好句子大全
第一句子网 > Java向将指定文件(含文件列表)或者指定路径下目录打包成zip格式

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

时间:2019-06-07 04:26:16

相关推荐

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

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

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

运行环境

1、springboot 2.2.x2、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: /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 = .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 = .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:/工作目录//5月/-12/今日工作需求.txt");srcFiles.add("D:/工作目录//5月/-12/完成情况.txt");ZipFiles(srcFiles, "D:\\工作目录\\\\5月\\-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: /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压缩包,如下:

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。