//Append content to the text file. If append=true, it will be appended by default. If append=false, the file will be emptied before appending the content. public static boolean updateContent(String fileName,String content,boolean append){ boolean res = true; File file = new File(fileName); try { if (!file.exists()) { file.createNewFile(); } FileWriter writer = new FileWriter(file,append); if(append){ content = System.getProperty("line.separator")+content; System.out.println(content); } writer.write(content); writer.flush(); writer.close(); } catch (IOException ex) { res = false; ex.printStackTrace(); } return res; }
It is important to note that FileWriter has only one parameter constructor, which will clear the original file by default!
FileWriter fw = new FileWriter(file);