生成多个文件,并打包成压缩包,在网页上下载。

网页:

<a href="${ctx}/tactivity/redPacketDetailsZip?activityid=${activityid }" target="_blank">导出昨日openid</a>

java代码:

    /**
     * 导出zip文件。zip内是txt文件。txt文件内是500个openid。openid一个一行。
     * @author xuyong
     * @date 2014-09-26
     */
    @RequestMapping(value = "/redPacketDetailsZip")
    public String redPacketDetailsZip(ModelMap model,
            TtakepartQuery query, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        logger.info("redPacketDetailsZip 微信红包导出zip文件 start...");
        
        // 查询条件 活动ID为activityid,and参与时间小于DateUtil.getCurrentDate(DateUtil.DATE_FMT) 的10000名未发送过得记录
        String activityidstr = request.getParameter("activityid"); // 活动ID
        Tactivity tactivity = tactivityManager.getById(Long.valueOf(activityidstr));
        Long activityid = new Long(activityidstr);
        query.setSendTimeZip(DateUtil.getCurrentDate(DateUtil.DATE_FMT)); // 年月日,时间小于此时间的参与
        query.setActivityid(activityid);//活动
        
        query.setSortColumns("t.createtime desc "); // 排序
        query.setPageSize(10000); // 条数
        Page page = ttakepartManager.findPage(query);
        logger.info("生成文件 文件....");
        String zipFileName = this.saveFile(request, tactivity.getShopid(), page.getResult());
        logger.info("生成文件 下载地址....");
        OutputStream o = response.getOutputStream();  
        byte b[] = new byte[1024];  
        File fileLoad = new File(zipFileName);  
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileLoad.getName(),"utf-8"));
        response.setContentType("application/zip");  // set the MIME type.   
        response.setHeader("Content_Length", String.valueOf(fileLoad.length())); // get the file length.
        FileInputStream in = new FileInputStream(fileLoad);  // download the file.  
        int n = 0;  
        while ((n = in.read(b)) != -1) {  
            o.write(b, 0, n);  
        }
        logger.info("redPacketDetailsZip 微信红包导出zip文件 end.");
        return null;
    }
/**保存文件,并且声称压缩包,返回压缩包地址
     * 
     * @date Nov 20, 20142:06:25 PM
     * @param resultList
     * @return 压缩包地址
     * @throws IOException 
     */
    private String saveFile(HttpServletRequest request, Long shopid, List resultList) throws IOException{
        logger.info("生成文件 start....");
        String zippath = DateUtil.getCurrentDateStr(DateUtil.DATE_FMT)+resultList.size()+"openid压缩包.zip"; // 上传文件路径
        int pageSize = 3;// 每个文件存储大小500
        String txtFullPath = "文件名称";
        StringBuffer openidBuffer = new StringBuffer(100); // openid内容
        List<File> allFilesList = new ArrayList<File>();//  文件集合
        // 保存导出文件。最多20个txt
        logger.info("生成文件 txt文件 start...");
        for (int i=0;i<resultList.size();i++){
            Ttakepart ttakepart = (Ttakepart)resultList.get(i);
            if (i%pageSize==0 && i>0){
                txtFullPath = FileUtil.getFilePath(request, Constant.CARDDOWN_PATH, shopid, i+".txt");
                logger.info("生成文件 txt文件 txtFullPath="+txtFullPath);
                // 创建保存文件
                FileUtil.saveOneFile(txtFullPath, openidBuffer.toString());
                allFilesList.add(new File(txtFullPath));
                // 重置内容
                openidBuffer = new StringBuffer(100);
            }
            
            openidBuffer.append(ttakepart.getWxno()).append("
"); // openid内容
        }
        if (openidBuffer.length() > 0){// 还存在文件剩余内容,保存文件
            txtFullPath = FileUtil.getFilePath(request, Constant.CARDDOWN_PATH, shopid, "last.txt");
            logger.info("生成文件 txt文件 txtFullPath="+txtFullPath);
            // 创建保存文件
            FileUtil.saveOneFile(txtFullPath, openidBuffer.toString());
            allFilesList.add(new File(txtFullPath));
            // 重置内容
            openidBuffer = new StringBuffer(100);
        }
        logger.info("生成文件 txt文件 end...");

        logger.info("压缩txt文件 start...");
        // 删除原有文件
        File zipFile = new File(zippath);
        if(zipFile.exists()){
            zipFile.delete();
        }
        
        zippath = FileUtil.getFilePath(request, Constant.CARDDOWN_PATH, shopid, zippath);
        // 压缩文件打包
        byte[] buffer = new byte[1024];
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zippath));
        //通过相应的业务来封装自己的list。
        FileInputStream fis = null;
        for (File eachFile : allFilesList) {
            fis = new FileInputStream(eachFile);
            out.putNextEntry(new ZipEntry(eachFile.getName()));
            int len;
            while ((len = fis.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
            out.closeEntry();
            fis.close();

            logger.info("删除文件 txt文件 txtFullPath="+eachFile.getCanonicalPath());
            eachFile.delete();
        }
        out.close();
        logger.info("压缩txt文件 end.");

        logger.info("生成文件 end....zippath="+zippath);
        return zippath;
    }
/**保存文件
     * 
     * @date Nov 20, 20144:27:49 PM
     * @param txtFullPath 文件全路径
     * @param fileContent 文件内容
     * @throws IOException
     */
    public static void saveOneFile(String fullPath, String fileContent) throws IOException
    {
        File file = new File(fullPath);
        // 创建文件
        if (!file.exists()){
            if(!file.getParentFile().exists()){
                file.getParentFile().mkdirs(); // 创建目录
            }
            file.createNewFile();
        }
        // 保存文件
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));
        bufferedOutputStream.write(fileContent.toString().getBytes()); 
        bufferedOutputStream.close();// 写入内容
    }
原文地址:https://www.cnblogs.com/a393060727/p/4110947.html