How to append content to file in Java

In Java, you can use PrintWriter(file,true) to append new content to the end of a file and this will keep the existing content and append the new content to the end of a file.
import java.io.*; public class TestClass{ public static void main(String[] args) { try { PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("in.txt", true))); //the true will append the new data out.println("New line append here !!"); out.close(); } catch (IOException e) { System.out.println(e); } } }
Also, as of Java 7 , you can use a try-with-resources statement. No finally block is required for closing the declared resource(s) because it is handled automatically, and is also less verbose.
import java.io.*; public class TestClass{ public static void main(String[] args) { try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("in.txt", true)))) { out.println("New line append here !!"); }catch (IOException e) { System.err.println(e); } } }