Java实现文本创建并追加内容
1,创建文本代码:
//创建文件并追加内容 public static void writeContentToTxt(StringBuffer Content,File f){ FileWriter fw = null; try { //如果文件存在,则追加内容;如果文件不存在,则创建文件 //File f=new File("D:\\hei.txt"); fw = new FileWriter(f, true); } catch (IOException e) { e.printStackTrace(); } PrintWriter pw = new PrintWriter(fw); pw.println(Content); pw.flush(); try { fw.flush(); pw.close(); fw.close(); } catch (IOException e) { e.printStackTrace(); } }
2,追加内容到文本:
public boolean saveText(List<BaseInfo> list ){ Date dt=new Date(); SimpleDateFormat matter1=new SimpleDateFormat("yyyyMMdd"); String date = matter1.format(dt); boolean flag = true; String filefullpath = Pub.getPropertiesValue("analysis", "dataPathDir")+"_.txt"; File anaylisisFile = new File (filefullpath); for(BaseInfo baseInfo : list ){ StringBuffer suf = new StringBuffer(); suf.append(date); suf.append("|&@"); suf.append(baseInfo.getOp_station()); suf.append("|&@"); suf.append(baseInfo.getIp()); suf.append("|&@"); suf.append(baseInfo.getMac()); suf.append("|&@"); suf.append(baseInfo.getPhone()); suf.append("|&@|"); logger.info("saveTxt suf:"+suf); writeContentToTxt(suf,anaylisisFile); } return flag; }