jsp请求压缩导出txt文件

@RequestMapping({ "/productDetailBurn_export.html" })
@ResponseBody
public void productDetailBurn_export(ProductDetailInfo productDetailInfo,
HttpServletRequest request, HttpServletResponse response)throws IOException {
	DbContextHolder.setDbType("isap");
	ModelAndView modelAndView = new ModelAndView();
	ProductInfo pro = (ProductInfo) request.getSession().getAttribute("mainProduct");//产品信息


	if ((pro != null) && (pro.getProductId() != null)) {

		//获取当前产品绑定用户信息
		Developer dev = new Developer();
		dev.setPageNum(0);
		dev.setPageSize(10);
		dev.setAcctId(pro.getAcctId());
		List<Developer> developers = this.developerService.selectDeveloper(dev);
		Developer developer =developers.get(0);
		String openid = developer.getOpenId();

		Integer pageNum = Integer.valueOf(1);
		if (request.getParameter("pageNum") != null) {
			pageNum = Integer.valueOf(Integer.parseInt(request.getParameter("pageNum")));
		}

		productDetailInfo.setPageNum(Integer.valueOf((pageNum.intValue() - 1) * 10));
		productDetailInfo.setPageSize(Integer.valueOf(10));
		List strs = = this.productDetailInfoService.selectProductDetailBurn(productDetailInfo);//导出数据查询



		Map<String,Object> maps = new HashMap<String,Object>();
		maps.put("open_id", openid);
		List<Map<String,Object>> daList = this.developerService.selectDomainNameAddress(maps);//导出数据替换
		List newStrs = new ArrayList();
    
    
		//组装用户域名地址信息
		if(strs.size() > 0 ){
			StringBuffer sbt = new StringBuffer();
			String st =null;
			if(daList.size() > 0 ){
				sbt.append("hostcnt=").append(daList.size()).append(";");
				for(int i = 0;i<daList.size();i++){
					sbt.append("host").append(i+1).append("=").append(daList.get(i).get("domain_name")).append(";");
				}
				st = sbt.substring(0, sbt.length()-1);
			}else{
			st="hostcnt=3;host1=box1.xcloudlink.com;host2=box2.xcloudlink.com;host3=box3.xcloudlink.com";
			}
			for(int j = 0 ;j<strs.size();j++){
				strs.get(j).toString().replace("host_count_name", st);
				newStrs.add(strs.get(j).toString().replace("host_count_name", st));
			}
		}
    
    
		String spNum = String.valueOf(request.getParameter("splitNumber"));
    
		List exList = new ArrayList();//拆分存储数据
		List ruList = new ArrayList();//存放拆分后数据
		if(spNum != null && !spNum.equals("")){
			double splitNumber = Double.valueOf(spNum);//拆分数量
			double a = newStrs.size();//查询结果总条数
			double c = a/splitNumber;
			double d = Math.ceil(c);//每个文件中存放数量
    
			for(int h = 0;h<newStrs.size();h++){
				exList.add(newStrs.get(h));
				if(exList.size()== d){
					String rust = sendProductInfoExport(exList);//list数据拼接成string返回
					ruList.add(rust);
					exList.clear();//清除己拆分后集合数据
				}else if(h == newStrs.size()-1){
					String rust = sendProductInfoExport(exList);//list数据拼接成string返回
					ruList.add(rust);
					exList.clear();//清除己拆分后集合数据
				}
			}
    
    
			//循环存储无拆分数据 start
			StringBuffer write = new StringBuffer();
			String enter = "\r\n";
			if (newStrs.size() > 0) {
				for (int i = 0; i < newStrs.size(); i++) {
					write.append((String) newStrs.get(i));
					write.append(enter);
				}
			}
			ruList.add(write.toString());
			//循环存储无拆分数据 end
    
		}else{
			//循环存储无拆分数据 start
			StringBuffer write = new StringBuffer();
			String enter = "\r\n";
			if (newStrs.size() > 0) {
				for (int i = 0; i < newStrs.size(); i++) {
					write.append((String) newStrs.get(i));
					write.append(enter);
				}
			}
			ruList.add(write.toString());
			//循环存储无拆分数据 end
		}
    
    
    
	response.setContentType("text/plain");
	String fileName = "devices";
	try {
		fileName = URLEncoder.encode("devices", "UTF-8");
	} catch (UnsupportedEncodingException e1) {
		e1.printStackTrace();
	}
	List filesName = new ArrayList();//文件名
	String filUrl = "";//文件路径
	// String url = "c:\\";//指定文件目录
	String url = "ownerManager/";//自己命名
	String writePath = "";
	if(ruList.size() > 0){
		for(int j = 0;j<ruList.size();j++){
			response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".txt");
			BufferedOutputStream buff = null;
			ServletOutputStream outSTr = null;
			try {
				outSTr = response.getOutputStream();
				buff = new BufferedOutputStream(outSTr);

				//定义文件名格式并创建  
				// 5.保存文件到filePath中
				String realPath = request.getSession().getServletContext().getRealPath("/");//获取项目在容器中的实际发布运行根路径
				File file1 = new File(realPath+ url.substring(0, url.lastIndexOf("/")));
				if (!file1.exists())
					file1.mkdirs();
					writePath = realPath + url;

					filUrl = writePath;

				File txtFile = File.createTempFile(fileName+j, ".txt", new File(writePath));  
				filesName.add(txtFile);//文件名称
				FileWriter writer =   new FileWriter(txtFile, true);  
               writer.write((String) ruList.get(j));  
               writer.flush();
               writer.close();

			} catch (Exception e) {
				e.printStackTrace();
			} 
		}
	}



   //-------------压缩文件start   //设置压缩流:直接写入response,实现边压缩边下载
	//响应头的设置
     response.setCharacterEncoding("utf-8");
     response.setContentType("multipart/form-data");

    //设置压缩包的名字
    //解决不同浏览器压缩包名字含有中文时乱码的问题
    String downloadName = "烧入数据导出.zip";//压缩包名
    String agent = request.getHeader("USER-AGENT");   
    try {
           if (agent.contains("MSIE")||agent.contains("Trident")) {
               downloadName = java.net.URLEncoder.encode(downloadName, "UTF-8");
           } else {
               downloadName = new String(downloadName.getBytes("UTF-8"),"ISO-8859-1");
           }
       } catch (Exception e) {
           e.printStackTrace();
       }
       response.setHeader("Content-Disposition", "attachment;fileName=\"" + downloadName + "\"");
            
            ZipOutputStream zipos = null;
            try {
                zipos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
                zipos.setMethod(ZipOutputStream.DEFLATED); //设置压缩方法 
            } catch (Exception e) {
                e.printStackTrace();
            }

            //循环将文件写入压缩流
            DataOutputStream os = null;
            for(int i = 0; i < filesName.size(); i++ ){
            
                File file = new File(filesName.get(i).toString());
                try {
                    //添加ZipEntry,并ZipEntry中写入文件流
                    //这里,加上i是防止要下载的文件有重名的导致下载失败
                String st = filesName.get(i).toString();
                
                st =st.substring(st.lastIndexOf("\\"), st.length()-4);//windows环境下
			  //st =st.substring(st.lastIndexOf("/"), st.length()-4);linux环境下
                st = st.substring(1, st.length());
                
                    zipos.putNextEntry(new ZipEntry(i + st));
                    os = new DataOutputStream(zipos);
                    InputStream is = new FileInputStream(file);
                    byte[] bs = new byte[100];
                    int length = 0;
                    while((length = is.read(bs))!= -1){
                        os.write(bs, 0, length);
                    }
                    is.close();
                    zipos.closeEntry();
                } catch (IOException e) {
                    e.printStackTrace();
                } 
            }
            //关闭流
            try {
                os.flush();
                os.close();
                zipos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }


            /**
             * 删除文件
             */
//            for(int h  = 0;h<filesName.size();h++){
//             String st = filesName.get(h).toString();
//             st = st.substring(3, st.length());
//             deleteFile(filUrl,st);
          // }
          //---------------------------压缩文件end


	} else {
		modelAndView.setViewName("redirect:/productinfo/productList.html");//跳转
	}
}



/**
* 导出烧入数据拆分
* 2017-7-12
* @param response
* @param num
* @param newStrs
*/
public String sendProductInfoExport(List newStrs){
	String st="";
	StringBuffer write = new StringBuffer();
	String enter = "\r\n";
	try {
		if (newStrs.size() > 0) {
			for (int i = 0; i < newStrs.size(); i++) {
				write.append((String) newStrs.get(i));
				write.append(enter);
			}
		}
		st = write.toString();
	} catch (Exception e) {
		e.printStackTrace();
	} 
	return st;
}
 /**
    * 删除该目录filePath下的所有文件
    * @param filePath
    *            文件目录路径
    */
   public static void deleteFiles(String filePath) {
       File file = new File(filePath);
       if (file.exists()) {
           File[] files = file.listFiles();
           for (int i = 0; i < files.length; i++) {
               if (files[i].isFile()) {
                   files[i].delete();
               }
           }
       }
   }
 
   /**
    * 删除单个文件
    * @param filePath 文件目录路径
    * @param fileName 文件名称
    */
   public static void deleteFile(String filePath, String fileName) {
       File file = new File(filePath);
       if (file.exists()) {
           File[] files = file.listFiles();
           for (int i = 0; i < files.length; i++) {
               if (files[i].isFile()) {
                   if (files[i].getName().equals(fileName)) {
                       files[i].delete();
                       return;
                   }
               }
           }
       }
   }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
>