我们在开发的时候会遇到各种导出文件的情况,有的需要导出excel
JAVA导出EXCEL通用型
JAVA导出EXCEL定制型
但是有的需要导出txt文件。txt文件如何操作呢。
首先有导出txt方法,如下,其中text就是需要导出的内容
/* 导出txt文件
* @author
* @param response
* @param text 导出的字符串
* @return
*/
public void exportTxt(HttpServletResponse response, String text) {
response.setCharacterEncoding("utf-8");
//设置响应的内容类型
response.setContentType("text/plain");
//设置文件的名称和格式
response.addHeader("Content-Disposition", "attachment;filename="
+ genAttachmentFileName(DateUtil.getNowShortStringDate(), "JSON_FOR_UCC_")//设置名称格式,没有这个中文名称无法显示
+ ".txt");
BufferedOutputStream buff = null;
ServletOutputStream outStr = null;
try {
outStr = response.getOutputStream();
buff = new BufferedOutputStream(outStr);
buff.write(text.getBytes("UTF-8"));
buff.flush();
buff.close();
} catch (Exception e) {
//LOGGER.error("导出文件文件出错:{}",e);
} finally {
try {
buff.close();
outStr.close();
} catch (Exception e) {
//LOGGER.error("关闭流对象出错 e:{}",e);
}
}
}