Java怎么把文件夹打成压缩包并导出

Java怎么把文件夹打成压缩包并导出

本篇内容介绍了“Java怎么把文件夹打成压缩包并导出”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

把文件夹打成压缩包并导出

1.打压缩包业务类

@ControllerpublicclassAdminController{privateStringfilePath=AdminController.class.getResource("/").getPath().split("WEB-INF")[0]+"upload/";@RequestMapping(value="export_zip.htm",method={RequestMethod.GET,RequestMethod.POST})publicvoidzipwordDownAction(HttpServletRequestrequest,HttpServletResponseresponse)throwsException{//打包文件的存放路径ZipCompressorByAntzc=newZipCompressorByAnt(filePath+"/file.zip");//需要打包的文件路径zc.compress(filePath+"/file/");StringcontentType="application/octet-stream";try{//导出压缩包download(request,response,"upload/file.zip",contentType,encodeChineseDownloadFileName(request,"file.zip"));}catch(Exceptione){request.getSession().setAttribute("msg","暂无内容");}//如果原压缩包存在,则删除Filefile=newFile(filePath+"/file.zip");if(file.exists()){file.delete();}}/***下载文件*/publicstaticvoiddownload(HttpServletRequestrequest,HttpServletResponseresponse,StringstoreName,StringcontentType,StringrealName)throwsException{response.setContentType("text/html;charset=UTF-8");request.setCharacterEncoding("UTF-8");BufferedInputStreambis=null;BufferedOutputStreambos=null;StringctxPath=FileUtil.class.getResource("/").getPath().split("WEB-INF")[0];StringdownLoadPath=ctxPath+storeName;longfileLength=newFile(downLoadPath).length();response.setContentType(contentType);response.setHeader("Content-disposition","attachment;filename="+newString(realName.getBytes("utf-8"),"ISO8859-1"));response.setHeader("Content-Length",String.valueOf(fileLength));bis=newBufferedInputStream(newFileInputStream(downLoadPath));bos=newBufferedOutputStream(response.getOutputStream());byte[]buff=newbyte[2048];intbytesRead;while(-1!=(bytesRead=bis.read(buff,0,buff.length))){bos.write(buff,0,bytesRead);}bis.close();bos.close();}/***对文件流输出下载的中文文件名进行编码屏蔽各种浏览器版本的差异性*/publicstaticStringencodeChineseDownloadFileName(HttpServletRequestrequest,StringpFileName)throwsUnsupportedEncodingException{Stringfilename=null;Stringagent=request.getHeader("USER-AGENT");if(null!=agent){if(-1!=agent.indexOf("Firefox")){//Firefoxfilename="=?UTF-8?B?"+(newString(org.apache.commons.codec.binary.Base64.encodeBase64(pFileName.getBytes("UTF-8"))))+"?=";}elseif(-1!=agent.indexOf("Chrome")){//Chromefilename=newString(pFileName.getBytes(),"ISO8859-1");}else{//IE7+filename=java.net.URLEncoder.encode(pFileName,"UTF-8");filename=StringUtils.replace(filename,"+","%20");//替换空格}}else{filename=pFileName;}returnfilename;}

2.调用工具类

importjava.io.File;importorg.apache.tools.ant.Project;importorg.apache.tools.ant.taskdefs.Zip;importorg.apache.tools.ant.types.FileSet;publicclassZipCompressorByAnt{privateFilezipFile;publicZipCompressorByAnt(StringpathName){zipFile=newFile(pathName);}publicvoidcompress(StringsrcPathName){Filesrcdir=newFile(srcPathName);if(!srcdir.exists())thrownewRuntimeException(srcPathName+"不存在!");Projectprj=newProject();Zipzip=newZip();zip.setProject(prj);zip.setDestFile(zipFile);FileSetfileSet=newFileSet();fileSet.setProject(prj);fileSet.setDir(srcdir);//fileSet.setIncludes("**/*.java");包括哪些文件或文件夹eg:zip.setIncludes("*.java");//fileSet.setExcludes(...);排除哪些文件或文件夹zip.addFileset(fileSet);zip.execute();}}

生成zip文件并导出

总结一下

关于Java下载zip文件并导出的方法,浏览器导出。

Java怎么把文件夹打成压缩包并导出

StringdownloadName="下载文件名称.zip";downloadName=BrowserCharCodeUtils.browserCharCodeFun(request,downloadName);//下载文件名乱码问题解决//将文件进行打包下载try{OutputStreamout=response.getOutputStream();byte[]data=createZip("/fileStorage/download");//服务器存储地址response.reset();response.setHeader("Content-Disposition","attachment;fileName="+downloadName);response.addHeader("Content-Length",""+data.length);response.setContentType("application/octet-stream;charset=UTF-8");IOUtils.write(data,out);out.flush();out.close();}catch(Exceptione){e.printStackTrace();}

获取下载zip文件流

publicbyte[]createZip(StringsrcSource)throwsException{ByteArrayOutputStreamoutputStream=newByteArrayOutputStream();ZipOutputStreamzip=newZipOutputStream(outputStream);//将目标文件打包成zip导出Filefile=newFile(srcSource);a(zip,file,"");IOUtils.closeQuietly(zip);returnoutputStream.toByteArray();}

publicvoida(ZipOutputStreamzip,Filefile,Stringdir)throwsException{//如果当前的是文件夹,则进行进一步处理if(file.isDirectory()){//得到文件列表信息File[]files=file.listFiles();//将文件夹添加到下一级打包目录zip.putNextEntry(newZipEntry(dir+"/"));dir=dir.length()==0?"":dir+"/";//循环将文件夹中的文件打包for(inti=0;i<files.length;i++){a(zip,files[i],dir+files[i].getName());//递归处理}}else{//当前的是文件,打包处理//文件输入流BufferedInputStreambis=newBufferedInputStream(newFileInputStream(file));ZipEntryentry=newZipEntry(dir);zip.putNextEntry(entry);zip.write(FileUtils.readFileToByteArray(file));IOUtils.closeQuietly(bis);zip.flush();zip.closeEntry();}}

“Java怎么把文件夹打成压缩包并导出”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注恰卡编程网网站,小编将为大家输出更多高质量的实用文章!

发布于 2022-02-07 23:14:20
收藏
分享
海报
0 条评论
51
上一篇:怎么用python实现文件备份 下一篇:Node.js中module.exports和exports使用误区是什么
目录

    0 条评论

    本站已关闭游客评论,请登录或者注册后再评论吧~

    忘记密码?

    图形验证码