Java匯出txt檔案
1、拼接需要匯出的String字串
/* 拼接字串 * @author * @param * @return */ @RequestMapping("exportLog.do") public void exportLog(HttpServletResponse response){ //獲取日誌 List<DtmSystemLog> list = logService.getLogs(); //拼接字串 StringBuffer text = new StringBuffer(); for(DtmSystemLog log:list){ text.append(log.getOpeuser()); text.append("|"); text.append(log.getOpedesc()); text.append("|"); text.append(dateString); text.append("\r\n");//換行字元 } exportTxt(response,text.toString()); }
/* 匯出txt檔案 * @author * @paramresponse * @paramtext 匯出的字串 * @return */ public void exportTxt(HttpServletResponse response,String text){ response.setCharacterEncoding("utf-8"); //設定響應的內容型別 response.setContentType("text/plain"); //設定檔案的名稱和格式 response.addHeader("Content-Disposition","attachment;filename=" + genAttachmentFileName( "檔名稱", "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); } } }
//防止中文檔名顯示出錯
public String genAttachmentFileName(String cnName, String defaultName) {
try {
cnName = new String(cnName.getBytes("gb2312"), "ISO8859-1");
} catch (Exception e) {
cnName = defaultName;
}
return cnName;
}