欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-16 15:22:32
目录把文件夹打成压缩包并导出1.打压缩包业务类2.调用工具类生成zip文件并导出总结一下获取下载zip文件流把文件夹打成压缩包并导出1.打压缩包业务类@controllerpublic class a...

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

1.打压缩包业务类

@controller
public 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(httpservletrequest request,httpservletresponse response) throws exception {
        //打包文件的存放路径                     
        zipcompressorbyant zc = new  zipcompressorbyant(filepath+ "/file.zip");
        //需要打包的文件路径
        zc.compress(filepath+ "/file/");
        string contenttype = "application/octet-stream";
        try {
            //导出压缩包
            download(request, response, "upload/file.zip", contenttype,encodechinesedownloadfilename(request, "file.zip"));
        } catch (exception e) {
            request.getsession().setattribute("msg", "暂无内容");
        }
        //如果原压缩包存在,则删除
        file file=new file(filepath+ "/file.zip");
        if(file.exists()){
            file.delete(); 
        }
    }   
    /** 
     * 下载文件  
     */  
    public static void download(httpservletrequest request,httpservletresponse response, string storename, string contenttype,string realname) throws exception {
        response.setcontenttype("text/html;charset=utf-8");
        request.setcharacterencoding("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();
        response.setcontenttype(contenttype);
        response.setheader("content-disposition", "attachment; filename="
                + new string(realname.getbytes("utf-8"), "iso8859-1"));
        response.setheader("content-length", string.valueof(filelength));
        bis = new bufferedinputstream(new fileinputstream(downloadpath));
        bos = new bufferedoutputstream(response.getoutputstream());
        byte[] buff = new byte[2048];
        int bytesread;
        while (-1 != (bytesread = bis.read(buff, 0, buff.length))) {
            bos.write(buff, 0, bytesread);
        }
        bis.close();
        bos.close();
    }
    /** 
     * 对文件流输出下载的中文文件名进行编码 屏蔽各种浏览器版本的差异性  
     */  
    public static string encodechinesedownloadfilename(httpservletrequest request, string pfilename) throws unsupportedencodingexception {  
         string filename = null;    
            string agent = request.getheader("user-agent");    
            if (null != agent){    
                if (-1 != agent.indexof("firefox")) {//firefox    
                    filename = "=?utf-8?b?" + (new string(org.apache.commons.codec.binary.base64.encodebase64(pfilename.getbytes("utf-8"))))+ "?=";    
                }else if (-1 != agent.indexof("chrome")) {//chrome    
                    filename = new string(pfilename.getbytes(), "iso8859-1");    
                } else {//ie7+    
                    filename = java.net.urlencoder.encode(pfilename, "utf-8");    
                    filename = stringutils.replace(filename, "+", "%20");//替换空格    
                }    
            } else {    
                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.fileset;
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.setproject(prj);  
        zip.setdestfile(zipfile);  
        fileset fileset = new fileset();  
        fileset.setproject(prj);   
        fileset.setdir(srcdir);  
        //fileset.setincludes("**/*.java"); 包括哪些文件或文件夹 eg:zip.setincludes("*.java");  
        //fileset.setexcludes(...); 排除哪些文件或文件夹  
        zip.addfileset(fileset);            
        zip.execute();  
    }  
}

生成zip文件并导出

总结一下

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

string downloadname = "下载文件名称.zip";
        downloadname = browsercharcodeutils.browsercharcodefun(request, downloadname);//下载文件名乱码问题解决
        
        //将文件进行打包下载
        try {
            outputstream out = 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 (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.closequietly(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());         //递归处理
                }
            } else {   //当前的是文件,打包处理
                //文件输入流
               bufferedinputstream bis = new bufferedinputstream(new fileinputstream(file));
               zipentry entry = new zipentry(dir);
               zip.putnextentry(entry);
               zip.write(fileutils.readfiletobytearray(file));
               ioutils.closequietly(bis);
               zip.flush();
               zip.closeentry();
            }
    }

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