How to append content to file?
- new FileWriter(file,true) to append new content to the end of a file.
FileWriter(file,true) -> Keep the existing content and append the new content to the end of a file.
package com.nourit.javaIO; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class AppendContentToFile { public static void main(String[] args) throws IOException { BufferedWriter bufferedWriter = null; FileWriter fileWriter = null; try { String data = " This is new content"; File file = new File("D:/tmp/nourit.txt"); //if file doesnt exists, then create it if (!file.exists()) { file.createNewFile(); } // true = append file -> new FileWriter(file, append); fileWriter = new FileWriter(file.getAbsoluteFile(), true); bufferedWriter = new BufferedWriter(fileWriter); bufferedWriter.write(data); System.out.println("Content is Done"); } catch (IOException e) { e.printStackTrace(); } finally { if (bufferedWriter != null){ bufferedWriter.close(); } if (fileWriter != null){ fileWriter.close(); } } } }
Output:
Content is Done