JSF页面中导出txt文件

/**
* 导出txt文件
*/
public void exportTxt() {
HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
writeToTxt(httpServletResponse);
FacesContext.getCurrentInstance().responseComplete();
}

/**
* 写入数据到txt
* @param response
*/
public void writeToTxt(HttpServletResponse response) {

response.setContentType("text/plain");// 以纯文本的形式发送。
response.addHeader("Content-Disposition",
   "attachment;filename=data.txt");// filename指定默认的名字
BufferedOutputStream buff = null;
StringBuffer write = new StringBuffer();
String tab = ",";
String enter = "\r\n";
ServletOutputStream outSTr = null;
try {
   outSTr = response.getOutputStream();
   buff = new BufferedOutputStream(outSTr);
   write.append("测试数据1" + tab);
   write.append("测试数据2" + tab);
   write.append("测试数据3" + tab);
   write.append("测试数据4" + tab);
   write.append("测试数据5" + tab);
   write.append("测试数据6");
   write.append(enter);
   write.append("测试数据1" + tab);
   write.append("测试数据2" + tab);
   write.append("测试数据3" + tab);
   write.append("测试数据4" + tab);
   write.append("测试数据5" + tab);
   write.append("测试数据6");
   write.append(enter);

   buff.write(write.toString().getBytes("UTF-8"));
   buff.flush();
   buff.close();
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
  try {
   buff.close();
   outSTr.close();
  } catch (Exception e) {
   e.printStackTrace();
  }
}

}

//页面调用
<h:commandButton action="#{exportAction.exportTxt}" value="保存数据" />

你可能感兴趣的:(JSF)