Java压缩多个文件并导出
controller层:
- /**
- * 打包压缩下载文件
- */
- @RequestMapping(value = "/downLoadZipFile")
- public void downLoadZipFile(HttpServletResponse response) throws IOException{
- String zipName = "myfile.zip";
- List<FileBean> fileList = fileService.getFileList();//查询数据库中记录
- response.setContentType("APPLICATION/OCTET-STREAM");
- response.setHeader("Content-Disposition","attachment; filename="+zipName);
- ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
- try {
- for(Iterator<FileBean> it = fileList.iterator();it.hasNext();){
- FileBean file = it.next();
- ZipUtils.doCompress(file.getFilePath()+file.getFileName(), out);
- response.flushBuffer();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }finally{
- out.close();
- }
- }
如果需要支持跨域,在controller中添加代码:
- response.setHeader("Access-Control-Allow-Origin", "*");
- response.setHeader("Access-Control-Allow-Method", "POST,GET");
压缩工具类:
- package com.m2plat.puhui.utils;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import java.io.*;
- import java.util.zip.ZipEntry;
- import java.util.zip.ZipOutputStream;
- /**
- * 文件压缩工具类
- * Created by xiangzh on 2018/11/20.
- */
- public class ZipUtils {
- private static Logger logger = LoggerFactory.getLogger(ZipUtils.class);
- private ZipUtils(){
- }
- public static void doCompress(String srcFile, String zipFile) throws IOException {
- doCompress(new File(srcFile), new File(zipFile));
- }
- /**
- * 文件压缩
- * @param srcFile 目录或者单个文件
- * @param zipFile 压缩后的ZIP文件
- */
- public static void doCompress(File srcFile, File zipFile) throws IOException {
- ZipOutputStream out = null;
- try {
- out = new ZipOutputStream(new FileOutputStream(zipFile));
- doCompress(srcFile, out);
- } catch (Exception e) {
- throw e;
- } finally {
- out.close();//记得关闭资源
- }
- }
- public static void doCompress(String filelName, ZipOutputStream out) throws IOException{
- doCompress(new File(filelName), out);
- }
- public static void doCompress(File file, ZipOutputStream out) throws IOException{
- doCompress(file, out, "");
- }
- public static void doCompress(File inFile, ZipOutputStream out, String dir) throws IOException {
- if ( inFile.isDirectory() ) {
- File[] files = inFile.listFiles();
- if (files!=null && files.length>0) {
- for (File file : files) {
- String name = inFile.getName();
- if (!"".equals(dir)) {
- name = dir + "/" + name;
- }
- ZipUtils.doCompress(file, out, name);
- }
- }
- } else {
- ZipUtils.doZip(inFile, out, dir);
- }
- }
- public static void doZip(File inFile, ZipOutputStream out, String dir) throws IOException {
- String entryName = null;
- if (!"".equals(dir)) {
- entryName = dir + "/" + inFile.getName();
- } else {
- entryName = inFile.getName();
- }
- ZipEntry entry = new ZipEntry(entryName);
- out.putNextEntry(entry);
- int len = 0 ;
- byte[] buffer = new byte[1024];
- FileInputStream fis = new FileInputStream(inFile);
- while ((len = fis.read(buffer)) > 0) {
- out.write(buffer, 0, len);
- out.flush();
- }
- out.closeEntry();
- fis.close();
- }
- public static void doZip(InputStream in ,ZipOutputStream out, String entryName) throws IOException {
- logger.info("---添加InputStream到压缩文件,InputStream大小:{}",in.available());
- ZipEntry entry = new ZipEntry(entryName);
- out.putNextEntry(entry);
- int len = 0 ;
- byte[] buffer = new byte[1024*5];
- while ((len = in.read(buffer)) > 0) {
- out.write(buffer, 0, len);
- out.flush();
- }
- out.closeEntry();
- in.close();
- }
- public static void main(String[] args) throws IOException {
- doCompress("D:/excel/puhui/1", "D:/附件.zip");
- }
- }
其他:spring mvc 下载普通单个文件的方法:
- @RequestMapping(value = "/downloadFile")
- @ResponseBody
- public void downloadFile (HttpServletResponse response) {
- OutputStream os = null;
- try {
- os = response.getOutputStream();
- File file = new File("D:/javaweb/demo.txt");
- // Spring工具获取项目resources里的文件
- File file2 = ResourceUtils.getFile("classpath:shell/init.sh");
- if(!file.exists()){
- return;
- }
- response.reset();
- response.setHeader("Content-Disposition", "attachment;filename=demo.txt");
- response.setContentType("application/octet-stream; charset=utf-8");
- os.write(FileUtils.readFileToByteArray(file));
- } catch (Exception e) {
- e.printStackTrace();
- }finally{
- IOUtils.closeQuietly(os);
- }
- }
补充,另外一种 利用 ResponseEntity<byte[]> 实现下载单个文件的方法:
- /**
- * Spring下载文件
- * @param request
- * @throws IOException
- */
- @RequestMapping(value="/download")
- public ResponseEntity<byte[]> download(HttpServletRequest request) throws IOException{
- // 获取项目webapp目录路径下的文件
- String path = request.getSession().getServletContext().getRealPath("/");
- File file = new File(path+"/soft/javaweb.txt");
- HttpHeaders headers = new HttpHeaders();
- headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
- headers.setContentDispositionFormData("attachment", "javaweb.txt");
- return new ResponseEntity<byte[]>(org.apache.commons.io.FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
- }
- <a target="_blank" href="/download">点击下载</a>
参考:
Java压缩多个文件并导出的更多相关文章
- 【转】Java压缩和解压文件工具类ZipUtil
特别提示:本人博客部分有参考网络其他博客,但均是本人亲手编写过并验证通过.如发现博客有错误,请及时提出以免误导其他人,谢谢!欢迎转载,但记得标明文章出处:http://www.cnblogs.com/ ...
- JAVA实用案例之文件导入导出(POI方式)
1.介绍 java实现文件的导入导出数据库,目前在大部分系统中是比较常见的功能了,今天写个小demo来理解其原理,没接触过的同学也可以看看参考下. 目前我所接触过的导入导出技术主要有POI和iRepo ...
- java压缩多个文件
首先创建一个工具类,定义好接口,这里的参数1:fileList:多个文件的path+name2: zipFileName:压缩后的文件名 下面是代码,注释已经很详细了 public class ZIP ...
- JAVA实用案例之文件导出(JasperReport踩坑实录)
写在最前面 想想来新公司也快五个月了,恍惚一瞬间. 翻了翻博客,因为太忙,也有将近五个多月没认真总结过了. 正好趁着今天老婆出门团建的机会,记录下最近这段时间遇到的大坑-JasperReport. 六 ...
- java如何压缩多个文件到压缩包,并下载到浏览器?
java压缩多个文件到压缩包,并下载到浏览器 解决方法: 完整的方法如下,很简单,亲试有效,极力推荐. 我是以流作为文件,而不是file,循环把所有pdf文件压缩到pdf.zip压缩包中. 1.前 ...
- Java Itext 生成PDF文件
利用Java Itext生成PDF文件并导出,实现效果如下: PDFUtil.java package com.jeeplus.modules.order.util; import java.io.O ...
- java压缩文件或文件夹并导出
java压缩文件或文件夹并导出 tozipUtil: package com.zhl.push.Utils; import java.io.File; import java.io.FileInput ...
- java实现多个文件以压缩包导出到本地
描述:使用java将多个文件同时压缩为压缩包,并导出到本地 /** *压缩文件并导出 */ public static void zipFiles() throws IOException { Fil ...
- JAVA核心技术I---JAVA基础知识(Jar文件导入导出)
一:Jar初识 (一)定义 同c++中的DLL一样 jar文件,一种扩展名为jar的文件,是Java所特有的一种文件格式,用于可执行程序文件的传播. jar文件实际上是一组class文件的压缩包 (二 ...
随机推荐
- Makefile--基本规则(零)
[版权声明:转载请保留出处:周学伟:http://www.cnblogs.com/zxouxuewei/] 一般一个稍大的linux项目会有很多个源文件组成,最终的可执行程序也是由这许多个源文件编译链 ...
- Mysql综合案例
Mysql综合案例 考核要点:创建数据表.单表查询.多表查询 已知,有一个学生表student和一个分数表score,请按要求对这两个表进行操作.student表和score分数表的表结构分别如表1- ...
- java中被遗忘的native关键字
我是无意间看见JNI( java调用动态链接库dll )这块的东西. 所有记下来:本地声明方法 装载完成dll文件后,将使用的方法用native关键字声明. public native static ...
- docker学习-docker容器
- idea & datagrip 注册码
CNEKJPQZEX-eyJsaWNlbnNlSWQiOiJDTkVLSlBRWkVYIiwibGljZW5zZWVOYW1lIjoibGFuIHl1IiwiYXNzaWduZWVOYW1lIjoiI ...
- UITextView和UITextField的placeholder,键盘隐藏,键盘换行变完成字样
本文转载至 http://blog.csdn.net/hengshujiyi/article/details/9086093- (void)initFeedBackViews { //设置页面的背景颜 ...
- Mybatis之typeAlias配置的3种方法
1.定义别名: <typeAliases> <typeAlias alias="User" type="cn.lxc.vo.User" /&g ...
- js将字符串转换为数字等类型
1.js提供了parseInt()和parseFloat()两个转换函数. 2.ECMAScript中可用的3种强制类型转换如下: Boolean(value)——把给定的值转换成Boolean型: ...
- iOS - 布局重绘机制相关方法的研究
iOS View布局重绘机制相关方法 布局 - (void)layoutSubviews - (void)layoutIfNeeded- (void)setNeedsLayout —————————— ...
- mac下搭建cocos2d-x2.2.1版本android编译环境教程
首先我们先以引擎2.2.1为例子来新建一个TestJni的项目,来作为测试例. 创建方式如下: python create_project.py -project TestJni -package o ...