java实现多文件压缩打包

来源:互联网 发布:怎么样能加入淘宝客 编辑:程序博客网 时间:2024/06/01 10:23

介绍了Java实现多文件压缩打包的方法,结合实例形式分析了java实现zip文件压缩与解压缩相关操作

package com.dengjiancai.util;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;import java.util.Enumeration;import java.util.zip.ZipEntry;import java.util.zip.ZipFile;import java.util.zip.ZipOutputStream;public class ZIPUtil {/**       * 功能:压缩多个文件成一个zip文件       * @param srcfile:源文件列表       * @param zipfile:压缩后的文件       */      public static void zipFiles(File[] srcfile,File zipfile){        byte[] buf=new byte[1024];        try {          //ZipOutputStream类:完成文件或文件夹的压缩          ZipOutputStream out=new ZipOutputStream(new FileOutputStream(zipfile));          for(int i=0;i<srcfile.length;i++){            FileInputStream in=new FileInputStream(srcfile[i]);            out.putNextEntry(new ZipEntry(srcfile[i].getName()));            int len;            while((len=in.read(buf))>0){              out.write(buf,0,len);            }            out.closeEntry();            in.close();          }          out.close();          System.out.println("压缩完成.");        } catch (Exception e) {          // TODO Auto-generated catch block          e.printStackTrace();        }      }      /**       * 功能:解压缩       * @param zipfile:需要解压缩的文件       * @param descDir:解压后的目标目录       */      public static void unZipFiles(File zipfile,String descDir){        try {          ZipFile zf=new ZipFile(zipfile);          for(Enumeration<? extends ZipEntry> entries=zf.entries();entries.hasMoreElements();){            ZipEntry entry=(ZipEntry) entries.nextElement();            String zipEntryName=entry.getName();            InputStream in=zf.getInputStream(entry);            OutputStream out=new FileOutputStream(descDir+zipEntryName);            byte[] buf1=new byte[1024];            int len;            while((len=in.read(buf1))>0){              out.write(buf1,0,len);            }            in.close();            out.close();            System.out.println("解压缩完成.");          }        } catch (Exception e) {          // TODO Auto-generated catch block          e.printStackTrace();        }      }public static void main(String args[]){        //2个源文件        File f1=new File("D:\\home\\mobpay\\app\\download\\2.jpg");        File f2=new File("D:\\home\\mobpay\\app\\download\\4.jpg");        File[] srcfile={f1,f2};        //压缩后的文件        File zipfile=new File("D:\\home\\mobpay\\app\\download\\whitelist.zip");        zipFiles(srcfile, zipfile);        //需要解压缩的文件        File file=new File("D:\\workspace\\flexTest\\src\\com\\biao\\test\\biao.zip");        //解压后的目标目录        String dir="D:\\workspace\\flexTest\\src\\com\\biao\\test\\";        //unZipFiles(file, dir);    }}

html页面处理,使用常用的jQuery+ajax方式提交,因页面展示的列表没有保存图片的地址,请求后台参数字段包含了每条记录Id ,调后台循环处理多个文件并压缩成一个zip包,最后返回服务器路径,主要代码如下:

        <div style="margin-top: 10px">            <span id="auth_btn">                <a  class="btn btn-small btn-add" id='download' href="#" onclick="downPic()">下载选中列表图片</a>            </span>         </div>        /* js方法*/function downPic(){        var rows = $('#grid-table').jqGrid("getGridParam", "selarrrow");        if (rows.length == 0) {            msg.alert("警告", "当前没有选择数据项!", "warn");            return;        }        var ids = "";        for (var i = 0; i < rows.length; i++) {            rowData = $('#grid-table').jqGrid('getRowData',rows[i]);            ids   = ids+rowData.signName+",";        }        ids = ids.substring(0, ids.lastIndexOf(","));        $.ajax({            type : "post",            url : "mpomng/whiteListBankInfManage/downloadPic.do?ids="+ids,            /* data:{"signName":ids}, */            dataType : 'json',            success : function(result) {                if(result.rspcod== 200){                    var a = $("<a href="+result.rspmsg+" download="+"0000.jpg"+" ></a>").get(0);                    var e = document.createEvent('MouseEvents');                    e.initEvent( 'click', true, true );                    a.dispatchEvent(e);                }else{                    msg.alert("错误", "文件不存在,请重新生成!", "error");                }            },            error: function() {                msg.alert('提示', "网络异常!",'error');            }        });      } /* jqGrid部分*/jQuery(grid_selector).jqGrid(                {                    url : "mpomng/whiteListBankInfManage/query.do",                    datatype : "json",                    height : '100%',                    width : '100%',                    colNames : [ '商户编号', 'id','操作' ],colModel:[                      {name:'custId',index:'custId',width:'120px'},                       {name:'signName',index:'signName',width:'none',hidden:true},                        {name:'op',index:'op',width:'100px',formatter:operateEdit}                                    ],                    viewrecords : true,                    rowNum : 20,                    rowList : [ 10, 20, 30 ],                    altRows : true,                    shrinkToFit : false,                    multiselect : true,//设置行可多选的                     multiboxonly : true,//                    loadComplete : function() {                        var table = this;                        setTimeout(function() {                            //加载分页                            initPagingBar(grid_selector);                        }, 0);                    },                    beforeRequest : function() {//请求之前执行                        jqGrid = this;                    },                });

控制器核心代码,包含有框架类可以忽略掉

@RequestMapping(value = "whiteListBankInfManage/downloadPic")    @ResponseBody    public ReturnMsg DownLoadPic(String ids) {        log.info("参数是{}",ids);        ReturnMsg rm = new ReturnMsg();        Map<String, Object> paramMap = null;        if (ids.indexOf(",") < 0) {            ids = ids + ",";        }        String[] signName = ids.split(",");        String idPath = "";        try {            List<File> srcfileList = new ArrayList<File>();            for (int i = 0; i < signName.length; i++) {                paramMap = new HashMap<String, Object>();                paramMap.put("signName", signName[i]);                String path = getPicPath(paramMap);                if(!"".equals(path)){                    srcfileList.add(new File(path));                }            }            idPath = queryLoadZipPath(srcfileList);            if(!"".equals(idPath)){                //rm.setMsg("path", idPath);                rm.setMsg("200", idPath);            }else{                rm.setMsg("201", "文件不存在");            }        } catch (Exception e) {            rm.setMsg("500", "下载失败");            e.printStackTrace();        }        return rm;    }//根据ID获取图片路径    public String getPicPath(Map<String,Object> param) throws Exception{        Map<String,Object> picMap = null;        String picPath = "";        picMap = getPicURL(param);//取得图片相对路径        if(picMap != null && !picMap.isEmpty() ){            if(!"".equals(picMap.get("fjPath"))){                picPath = picMap.get("fjPath").toString();            }        }        return picPath;    }//打包压缩多个文件,返回zip包路径,前端记得加上上下午路径public String queryLoadZipPath(List<File> srcfileList) {        String zipPath = "";        String path_1 ="";        String path_2 ="";        String path_3 ="";        String date = TdExpBasicFunctions.GETDATETIME("YYMMDD");        String fileName = TdExpBasicFunctions.GETDATETIME() + TdExpBasicFunctions.RANDOM(2, "4");        path_1 = String.valueOf(propMPBase.get("FILE_DOWNLOAD_PATH_1"));        path_2 = date + "/" + fileName + ".zip";        path_3 = String.valueOf(propMPBase.get("FILE_DOWNLOAD_PATH_2"));        if(!new File(path_2).isDirectory()){//判断路径是否存在            FileUtil.createDir(path_1+date);        }        File zipfile=new File(path_1 + path_2);        ZipUtil.zipFiles(srcfileList, zipfile);//打包文件        if(zipfile.exists()){            zipPath=zipfile.getPath();        }        String relativePath = path_3+path_2;        log.info("文件地址是{}",zipPath);        return relativePath;    }