-
2019-05-23 17:44:01
1、controller层
/** * 压缩打包文件下载到浏览器默认路径 * @return */ @RequestMapping(value="/downloadZipFile") @ResponseBody public Object compressedFile(@RequestParam(value = "docIds",required = false)String docIds){ List<File> files=new ArrayList<>(); List<String> list=new ArrayList<>(); String[] idList =docIds.split(","); for (String id:idList){ list.add(id); } List<DocManager> atttendanchList = docManagerService.selByAttendanceId(list); for (DocManager docManager:atttendanchList){ File file = new File(docManager.getDocPath()+docManager.getFileName()); files.add(file); } //将多个文件压缩打包,下载到默认浏览器 try { File zipFile=FileUtil.fileToZip(files,zipFilePath,ContentUtil.randomGen(6));//将多文件打包为zip文件 FileSystemResource fileSource = new FileSystemResource(zipFile); Object o = FileUtil.downloadFile(fileSource.getInputStream(), fileSource.getFilename()); zipFile.delete();//删除暂时存储的zip压缩包 return o; } catch (IOException e) { return MarkUtil.markRetunMsg(false,e.getMessage()); } }
2、FileUtil类中fileToZip方法,如下:
/** * 压缩文件 * @param files * @param zipFilePath * @param fileName * @return */ public static File fileToZip(List<File> files, String zipFilePath, String fileName) { File zipFile = new File(zipFilePath + "/" + fileName + ".zip"); new File(zipFilePath).mkdirs(); FileInputStream fis = null; BufferedInputStream bis = null; FileOutputStream fos = null; ZipOutputStream zos = null; try { fos = new FileOutputStream(zipFile); zos = new ZipOutputStream(new BufferedOutputStream(fos)); byte[] bufs = new byte[1024 * 10]; for (File file : files) { //创建ZIP实体,并添加进压缩包 String name=file.getName(); String reName=name.substring(0,name.length()-6);//修改文件名称,再保存到zip文件中 ZipEntry zipEntry = new ZipEntry(reName);//压缩 zos.putNextEntry(zipEntry);//将每个压缩文件保存到zip文件中 //读取待压缩的文件并写进压缩包里 fis = new FileInputStream(file); bis = new BufferedInputStream(fis, 1024 * 10); int read = 0; while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) { zos.write(bufs, 0, read); } } } catch (FileNotFoundException e) { e.printStackTrace(); throw new RuntimeException(e); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } finally { //关闭流 try { if (null != bis) bis.close(); if (null != zos) zos.close(); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } } return zipFile; }
3、FileUtil类中downloadFile方法,如下:
/** * 下载文件到默认浏览器 * @param in * @param fileName * @return */ public static ResponseEntity<InputStreamResource> downloadFile(InputStream in,String fileName) { try { byte[] testBytes = new byte[in.available()]; HttpHeaders headers = new HttpHeaders(); headers.add("Cache-Control", "no-cache, no-store, must-revalidate"); headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", MarkUtil.convertFileName(fileName))); headers.add("Pragma", "no-cache"); headers.add("Expires", "0"); return ResponseEntity .ok() .headers(headers) .contentLength(testBytes.length) .contentType(MediaType.parseMediaType("application/octet-stream")) .body(new InputStreamResource(in)); } catch (IOException e) { e.printStackTrace(); } return null; }
4、MarkUtil类中的convertFileName方法如下:
/** * chinese code convert * @param fileName * @return */ public static String convertFileName(String fileName) { if(isContainChinese(fileName)) { try { fileName = URLEncoder.encode(fileName, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } return fileName; }
欢迎转载,但是要注释来源,谢谢
作者:mengmeng233
来源:CSDN
原文:https://blog.csdn.net/mengmeng2222222/article/details/90484775
版权声明:本文为博主原创文章,转载请附上博文链接!更多相关内容 -
<ZIPUtil >java 打包文件(文件夹)为 zip压缩包 java 压缩文件
2019-04-09 01:01:55NULL 博文链接:https://alog2012.iteye.com/blog/1616684 -
java实现文件压缩打包(zip打包)(文件相关二)
2021-09-28 15:44:22一:将系统中的这几个文件进行压缩打包: 二:将位置和名称进行写死,然后运行如下:创建类:ZipOutputStreamDemo package com.example.test.fileUtils; import java.io.*; import java.util.ArrayList; ...一:将系统中的这几个文件进行压缩打包:
二:将位置和名称进行写死,然后运行如下:创建类:ZipOutputStreamDemo
package com.example.test.fileUtils; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * @ClassName ZipOutputStreamDemo * @Author houyuanbo * @Date 2021/9/28 15:14 * @Description TODO * @Version **/ public class ZipOutputStreamDemo { private static final Logger logger = LoggerFactory.getLogger(ZipOutputStreamDemo.class); public static void main(String[] args) throws IOException { List list = new ArrayList(); list.add("D:\\新建文件夹1\\"+"文档1.docx"); list.add("D:\\新建文件夹1\\"+"文档2.docx"); list.add("D:\\新建文件夹1\\"+"中国.txt"); list.add("D:\\新建文件夹1\\"+"美国.txt"); //定义压缩文件夹的名称和相关的位置 File zipFile = new File("D:\\新建文件夹\\" + "country.zip"); logger.info(""+zipFile); InputStream input = null; //定义压缩输出流 ZipOutputStream zipOut = null; //实例化压缩输出流 并定制压缩文件的输出路径 就是D盘下【D:\新建文件夹\country.zip】的位置处 zipOut = new ZipOutputStream(new FileOutputStream(zipFile)); for (Object o : list) { File file = new File((String) o); //定义输入文件流 input = new FileInputStream(file); zipOut.putNextEntry(new ZipEntry(file.getName())); //设置注释 zipOut.setComment("www.demo.com"); int temp = 0; while ((temp = input.read())!=-1){ zipOut.write(temp); } input.close(); } zipOut.close(); } }
三:运行结果如下:
完成
-
Java实现多文件压缩打包的方法
2020-08-30 09:06:48主要介绍了Java实现多文件压缩打包的方法,结合实例形式分析了java实现zip文件压缩与解压缩相关操作技巧,需要的朋友可以参考下 -
java将文件或是文件夹打包压缩成zip格式
2021-03-06 03:05:07导读热词下面是编程之家 jb51.cc 通过网络收集整理的代码...import java.io.BufferedInputStream;import java.io.DataInputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoun...导读热词
下面是编程之家 jb51.cc 通过网络收集整理的代码片段。
编程之家小编现在分享给大家,也给大家做个参考。
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*将文件或是文件夹打包压缩成zip格式
* @author ysc
*/
public class ZipUtils {
private static final Logger log = LoggerFactory.getLogger(ZipUtils.class);
private ZipUtils(){};
/**
* APDPlat中的重要打包机制
* 将jar文件中的某个文件夹里面的内容复制到某个文件夹
* @param jar 包含静态资源的jar包
* @param subDir jar中包含待复制静态资源的文件夹名称
* @param loc 静态资源复制到的目标文件夹
* @param force 目标静态资源存在的时候是否强制覆盖
*/
public static void unZip(String jar,String subDir,String loc,boolean force){
try {
File base=new File(loc);
if(!base.exists()){
base.mkdirs();
}
ZipFile zip=new ZipFile(new File(jar));
Enumeration extends ZipEntry> entrys = zip.entries();
while(entrys.hasMoreElements()){
ZipEntry entry = entrys.nextElement();
String name=entry.getName();
if(!name.startsWith(subDir)){
continue;
}
//去掉subDir
name=name.replace(subDir,"").trim();
if(name.length()<2){
log.debug(name+" 长度 < 2");
continue;
}
if(entry.isDirectory()){
File dir=new File(base,name);
if(!dir.exists()){
dir.mkdirs();
log.debug("创建目录");
}else{
log.debug("目录已经存在");
}
log.debug(name+" 是目录");
}else{
File file=new File(base,name);
if(file.exists() && force){
file.delete();
}
if(!file.exists()){
InputStream in=zip.getInputStream(entry);
FileUtils.copyFile(in,file);
log.debug("创建文件");
}else{
log.debug("文件已经存在");
}
log.debug(name+" 不是目录");
}
}
} catch (ZipException ex) {
log.error("文件解压失败",ex);
} catch (IOException ex) {
log.error("文件操作失败",ex);
}
}
/**
* 创建ZIP文件
* @param sourcePath 文件或文件夹路径
* @param zipPath 生成的zip文件存在路径(包括文件名)
*/
public static void createZip(String sourcePath,String zipPath) {
FileOutputStream fos = null;
ZipOutputStream zos = null;
try {
fos = new FileOutputStream(zipPath);
zos = new ZipOutputStream(fos);
writeZip(new File(sourcePath),"",zos);
} catch (FileNotFoundException e) {
log.error("创建ZIP文件失败",e);
} finally {
try {
if (zos != null) {
zos.close();
}
} catch (IOException e) {
log.error("创建ZIP文件失败",e);
}
}
}
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();
for(File f:files){
writeZip(f,parentPath,zos);
}
}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,len);
zos.flush();
}
} catch (FileNotFoundException e) {
log.error("创建ZIP文件失败",e);
} catch (IOException e) {
log.error("创建ZIP文件失败",e);
}finally{
try {
if(fis!=null){
fis.close();
}
}catch(IOException e){
log.error("创建ZIP文件失败",e);
}
}
}
}
}
public static void main(String[] args) {
ZipUtils.createZip("D:\\workspaces\\netbeans\\APDPlat\\APDPlat_Web\\target\\APDPlat_Web-2.2\\platform\\temp\\backup","D:\\workspaces\\netbeans\\APDPlat\\APDPlat_Web\\target\\APDPlat_Web-2.2\\platform\\temp\\backup.zip");
ZipUtils.createZip("D:\\workspaces\\netbeans\\APDPlat\\APDPlat_Web\\target\\APDPlat_Web-2.2\\platform\\index.jsp","D:\\workspaces\\netbeans\\APDPlat\\APDPlat_Web\\target\\APDPlat_Web-2.2\\platform\\index.zip");
}
}
以上是编程之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。
如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。
相关文章
总结
如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您喜欢交流学习经验,点击链接加入交流1群:1065694478(已满)交流2群:163560250
-
Java实现把文件及文件夹压缩成zip
2020-08-19 10:14:47主要介绍了Java实现把文件及文件夹压缩成zip,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 -
java实现一次性压缩多个文件到zip中的方法示例
2020-08-25 16:44:02主要介绍了java实现一次性压缩多个文件到zip中的方法,涉及java针对文件批量压缩相关的文件判断、遍历、压缩等操作技巧,需要的朋友可以参考下 -
java实现服务器文件打包zip并下载的示例(边打包边下载)
2020-09-04 12:21:06主要介绍了java实现服务器文件打包zip并下载的示例,使用该方法,可以即时打包文件,一边打包一边传输,不使用任何的缓存,让用户零等待,需要的朋友可以参考下 -
java后台批量下载文件并压缩成zip下载的方法
2020-08-27 05:04:01主要为大家详细介绍了java后台批量下载文件并压缩成zip下载的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下 -
Java多个文件根据URL下载后打包zip导出.zip
2021-04-16 09:52:13Java根据Url把多个文件下载到指定的文件夹目录,然后再将文件夹目录打包成zip导出,包括子目录也可以打包,有个简单的导出html页面,点击导出按钮下载zip。 -
java实现批量下载 多文件打包成zip格式下载
2020-08-25 19:52:24主要为大家详细介绍了java实现批量下载、将多文件打包成zip格式下载,具有一定的参考价值,感兴趣的小伙伴们可以参考一下 -
java将文件打包成ZIP压缩文件和解压缩zip文件
2019-04-21 01:10:30NULL 博文链接:https://rd-030.iteye.com/blog/1912370 -
JAVA 根据Url把多文件打包成ZIP下载实例
2020-08-29 17:49:28主要介绍了JAVA 根据Url把多文件打包成ZIP下载的相关资料,需要的朋友可以参考下 -
Java实现Zip压缩文件操作的工具类.zip
2021-06-09 17:34:30Java实现Zip压缩文件操作的工具类 文章介绍:https://blog.csdn.net/rongbo91/article/details/117747042 (可作为Jar依赖包直接使用) 1、项目使用前,请进入rdc-bom目录下,执行mvn clean install命令 2、可... -
java多个文件压缩打包成zip下载
2018-12-21 14:53:53java多个文件压缩打包成zip下载 如果实现批量操作一些文件,使之压缩打包成zip下载? 具体实现步骤如下: 设置下载文件名编码 创建zip输出流ZipOutputStream 将需要下载的文件流循环写入ZipOutputStream 关闭各个流...java多个文件压缩打包成zip下载
如果实现批量操作一些文件,使之压缩打包成zip下载?
具体实现步骤如下:- 设置下载文件名编码
- 创建zip输出流ZipOutputStream
- 将需要下载的文件流循环写入ZipOutputStream
- 关闭各个流
话不多说,直接上代码
service层方法(关键):@Override public void downloadAllFile(HttpServletResponse response, String processInstanceId) { String downloadName = "xxx附件.zip"; try { response.setContentType("multipart/form-data"); response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(downloadName, "UTF-8")); } catch (UnsupportedEncodingException e) { throw new HrmsException("下载文件名编码时出现错误.", e); } OutputStream outputStream = null; ZipOutputStream zos = null; try { outputStream = response.getOutputStream(); zos = new ZipOutputStream(outputStream); // 将文件流写入zip中 downloadTolocal(zos,processInstanceId); } catch (IOException e) { logger.error("downloadAllFile-xxx下载全部附件失败,processInstanceId=[{}],错误信息=[{}]",processInstanceId,e); }finally { if(zos != null) { try { zos.close(); } catch (Exception e2) { logger.info("关闭输入流时出现错误",e2); } } if(outputStream != null) { try { outputStream.close(); } catch (Exception e2) { logger.info("关闭输入流时出现错误",e2); } } } } private void downloadTolocal(ZipOutputStream zos,String processInstanceId) throws IOException { Map<String, String> pm = new HashMap<String, String>(); pm.put("processInstanceId", processInstanceId); //获取文件信息(此处为业务代码,可根据自己的需要替换) List<Map<String,String>> fileInfoList = this.findByStatement("getAllFileInfo",pm); for (Map<String, String> map : fileInfoList) { String fileId = map.get("fileId"); //文件名称(带后缀) String fileName = map.get("fileName"); InputStream is = null; BufferedInputStream in = null; byte[] buffer = new byte[1024]; int len; //创建zip实体(一个文件对应一个ZipEntry) ZipEntry entry = new ZipEntry(fileName); try { //获取需要下载的文件流 is = ossFileManager.getFile(fileId); in = new BufferedInputStream(is); zos.putNextEntry(entry); //文件流循环写入ZipOutputStream while ((len = in.read(buffer)) != -1 ) { zos.write(buffer, 0, len); } } catch (Exception e) { logger.info("xxx--下载全部附件--压缩文件出错",e); }finally { if(entry != null) { try { zos.closeEntry(); } catch (Exception e2) { logger.info("xxx下载全部附件--zip实体关闭失败",e2); } } if(in != null) { try { in.close(); } catch (Exception e2) { logger.info("xxx下载全部附件--文件输入流关闭失败",e2); } } if(is != null) { try { is.close(); }catch (Exception e) { logger.info("xxx下载全部附件--输入缓冲流关闭失败",e); } } } } }
controller层接口:
/** * 下载全部附件 */ @RequestMapping(value = "/downloadAllFile/{processInstanceId}", method = RequestMethod.GET) public void downloadAllFile(HttpServletResponse response,@PathVariable("processInstanceId") String processInstanceId) { floCnbCompetitionLimitService.downloadAllFile(response,processInstanceId); }
前端调用接口,便可在浏览器中直接下载zip文档下来
-
JAVA打包成.ZIP文件
2014-05-12 13:04:02JAVAWEB项目,实现将服务器文件打包成.zip文件,然后再下载到本地上。 -
Java Zip算法压缩多个文件的例子.rar
2019-07-10 12:34:37//得到待压缩文件路径名 String entryname=filename.substring(filename.lastIndexOf("\\") 1); //得到文件名 entry=new ZipEntry(entryname); //实例化条目列表 zout.putNextEntry(entry); //将ZIP条目... -
实例展示使用Java压缩和解压缩7z文件的方法
2020-09-03 04:53:02主要介绍了实例展示使用Java压缩和解压缩7z文件的方法,用到了7-zip的开源项目7-zip-JBinding,需要的朋友可以参考下 -
java多文件打包压缩工具类实现
2022-03-17 18:15:21概述:项目中有个多文件打包下载的需求,需要实现一个多文件打包的工具类,工具类基于jdk1.8的API。 我的需求:如下图 工具类实现: import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java... -
多个文件打包压缩下载
2018-05-03 17:33:45可以传入多个url地址,压缩成zip包下载,有更好的想法可以申请互动 -
java压缩文件,zip打包
2013-12-23 12:13:42应用java来压缩需要打包的文件,在系统管理中将毛哥路径或者某个文件夹压缩成zip包 -
Java8 Zip 压缩与解压缩的实现
2020-08-19 10:45:08主要介绍了Java8 Zip 压缩与解压缩的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧 -
JAVA文件压缩与解压缩实践(源代码+论文).zip项目JAVA源码+资料打包下载
2022-03-11 17:24:56JAVA文件压缩与解压缩实践(源代码+论文).zip项目JAVA源码+资料打包下载JAVA文件压缩与解压缩实践(源代码+论文).zip项目JAVA源码+资料打包下载 1.适合学生做毕业设计参考 2.适合个人学习技术研究参考 3.适合小公司做... -
java代码实现单个或多个文件压缩成rar包
2018-07-26 21:40:44java代码实现单个或多个文件压缩成rar包,本地要安装winRar插件。 -
java 操作Zip文件(压缩、解压、加密).zip
2020-08-21 17:19:55java 操作Zip文件(压缩、解压、加密) zip4j-1.3.2.jar ant-1.10.6.jar -
Java ZIP压缩一个或多个文件(解决中文名称乱码).rar
2020-04-11 23:19:42用java.util.zipoutputstream压缩会出现中文的文件名乱码的情况,且无法设置字符集,这个版本用org.apache.tools.zip.ZipOutputStream压缩,可以自定义字符集,解决中文的文件名乱码问题。 -
Java操作Ant压缩和解压文件及批量打包Anroid应用
2020-09-02 17:31:03主要介绍了使用Java操作Ant压缩和解压文件以及批量打包Anroid应用的教程,Ant是一个自动化部署工具,用来处理zip和tar文件非常方便,需要的朋友可以参考下 -
java压缩文件时的依赖jar包
2018-05-23 16:14:25java压缩文件时,必须要使用此jar包,之前试过别的很多方式,中文都会乱码 -
java实现将多个文件打包成zip压缩文件以及对压缩文件的加密
2021-02-28 13:19:09如果仅仅需要对文件进行压缩,方法比较简单,因为java的util包中提供了相关的压缩方法.首先,引入java.util.zip.ZipEntry,java.util.zip.ZipOutputStream包然后加入以下代码:String now = StringUtils.dateToString... -
java压缩批量文件打包
2012-05-03 11:05:18开发中经常遇到客户要求把一堆文件转为压缩文件打包下载,ant包可以实现此功能