首页 > 作文

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

更新时间:2023-04-04 20:07:51 阅读: 评论:0

目录
把文件夹打成压缩包并导出1.打压缩包业务类2.调用工具类生成zip文件并导出总结一下获取下载zip文件流

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

1.打压缩包业务类

@controllerpublic class admincontroller {    private string filepath = admincontroller.class.getresource("/").getpath().split("web-inf")[0]+ "upload/";        @requestmapping(value = "export_zip.htm", method = {requestmethod.get, requestmethod.post })    public void zipworddownaction(httprvletrequest request,httprvletrespon respon) throws exception {        //打包文件的存放路径                             zipcompressorbyant zc = new  zipcompressorbyant(filepath+ "/file.zip");        //需要打包的文件路径        zc.compress(filepath+ "/file/");        string contenttype = "application/octet-stream";        try {            //导出压缩包            download(request, respon, "upload/file.zip", contenttype,encodechinedownloadfilename(request, "file.zip"));        } catch (exception e) {            request.getssion()窈窕绅士.tattribute("msg", "暂无内容");        }        //如果原压缩包存在,则删除        file file=new file(filepath+ "/file.zip");        if(file.exists()){            file.delete();         }    }       /**      * 下载文件       */      public static void download(httprvletrequest request,httprvletrespon respon, string storename, string contenttype,string realname) throws exception {        respon.tcontenttype("text/html;chart=utf-8");        request.tcharacterencoding("utf-8");        bufferedinputstream bis = null;        bufferedoutputstream bos = null;        string ctxpath =fileutil.class.getresource("/").getpath().split("web-inf")[0];        string downloadpath = ctxpath + storename;        long filelength = new file(downloadpath).length();        respon.tcontenttype(contenttype);        respon.theader("content-disposition", "attachment; filename="                + new string(realname.getbytes("utf-8"), "iso8859-1"));        respon.theader("content-length", string.valueof(filelength));        bis = new bufferedinputstream(new fileinputstream(downloadpath));        bos = new bufferedoutput山东凯文stream(respon.getoutputstream());        byte[] buff = new byte[2048];        int bytesread;        while (-1 != (bytesread = bis.read(buff, 0, buff.length))) {            bos.write(buff, 0, bytesread);        }        bis.clo();        bos.clo();    }    /**      * 对文件流输出下载的中文文件名进行编码 屏蔽各种浏览器版本的差异性       */      public static string encodechinedownloadfilename(httprvletrequest request, string pfilename) throws unsupportedencodingexception {           string filename = null;                string agent = request.getheader("ur-agent");                if (null != agent){                    if (-1 != agent.indexof("firefox")) {//firefox                        filenasurvive的名词me = "=?utf-8?b?" + (new string(org.apache.commons.codec.binary.ba64.encodeba64(pfilename.getbytes("utf-8"))))+ "?=";                    }el if (-1 != agent.indexof("chrome")) {//chrome                        filename = new string(pfilename.getbytes(), "iso8859-1");                    } el {//ie7+                        filename = java.net.urlencoder.encode(pfilename, "utf-8");                        filename = stringutils.replace(filename, "+立秋吃饺子", "%20");//替换空格                    }                } el {                    filename = pfilename;                }                return filename;       }  

2.调用工具类

import java.io.file;import org.apache.tools.ant.project;import org.apache.tools.ant.taskdefs.zip;import org.apache.tools.ant.types.filet;public class zipcompressorbyant {    private file zipfile;      public zipcompressorbyant(string pathname) {          zipfile = new file(pathname);      }      public void compress(string srcpathname) {          file srcdir = new file(srcpathname);          if (!srcdir.exists())              throw new runtimeexception(srcpathname + "不存在!");          project prj = new project();          zip zip = new zip();              zip.tproject(prj);          zip.tdestfile(zipfile);          filet filet = new filet();          filet.tproject(prj);           filet.tdir(srcdir);          //filet.tincludes("**/*.java"); 包括哪些文件或文件夹 eg:zip.tincludes("*.java");          //filet.texcludes(...); 排除哪些文件或文件夹          zip.addfilet(filet);                    zip.execute();      }  }

生成zip文件并导出

总结一下

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

string downloadname = "下载文件名称.zip";    downloadname = browrcharcodeutils.browrcharcodefun(request, downloadname);//下载文件名乱码问题解决       //将文件进行打包下载    try {      outputstream out = respon.getoutputstream();      byte[] data = createzip("/filestorage/download");//服务器存储地址      respon.ret();      respon.theader("content-disposition","attachment;filename="+downloadname);      respon.addheader("content-length", ""+data.length);      respon.tcontenttype("application/octet-stream;chart=utf-8");      ioutils.write(data, out);      out.flush();      out.clo();    } catch (exception e) {      e.printstacktrace();    }

获取下载zip文件流

public byte[] createzip(string srcsource) throws exception{    bytearrayoutputstream outputstream = new bytearrayoutputstream();    zipoutputstream zip = new zipoutputstream(outputstream);    //将目标文件打包成zip导出    file file = new file(srcsource);    a(zip,file,"");    ioutils.cloquietly(zip);    return outputstream.tobytearray();  }
public void a(zipoutputstream zip, file file, string dir) throws exception {      //如果当前的是文件夹,则进行进一步处理      if (file.isdirectory()) {        //得到文件列表信息        file[] files = file.listfiles();        //将文件夹添加到下一级打包目录        zip.putnextentry(new zipentry(dir + "/"));        dir = dir.length() == 0 ? "" : dir + "/";        //循环将文件夹中的文件打包        for (int i = 澶渊之盟0; i < files.length; i++) {          a(zip, files[i], dir + files[i].getname());     //递归处理        }      } el {  //当前的是文件,打包处理        //文件输入流       bufferedinputstream bis = new bufferedinputstream(new fileinputstream(file));       zipentry entry = new zipentry(dir);       zip.putnextentry(entry);       zip.write(fileutils.readfiletobytearray(file));       ioutils.cloquietly(bis);       zip.flush();       zip.cloentry();      }  }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持www.887551.com。

本文发布于:2023-04-04 20:07:50,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/zuowen/33f87dd55dfba701f13635312e31dc42.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

本文word下载地址:Java如何把文件夹打成压缩包并导出.doc

本文 PDF 下载地址:Java如何把文件夹打成压缩包并导出.pdf

标签:文件   压缩包   文件夹   的是
相关文章
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图