Some times we need to append text into File in Java instead of creating new File. Thankfully Java File API is very rich and it provides several ways to append text into File in Java. Previously we have seen how to create file and directory in Java and how to read and write to text file in Java and in this Java IO tutorial we will see how to append text into file in Java. We are going to use standard FileWriter and BufferedWriter approach to append text to File. One of the key point to remember while using FileWriter in Java is to initialize FileWriter to append text i.e. writing bytes at the end of File rather than writing on beginning of the File. In next section we will see complete Java program to append text into File in Java. By the way you can also use FileOutputStream instead of FileWriter if you would like to write bytes, instead of text. Similar to FileWriter, FileOutputStream constructor also takes a boolean append argument to open connection to append bytes into File in Java.
Java program to append text to File in Java using FileWriter
In this section we will see a fully functional Java program which appends text at the end of File. In this program, we have used FileWriter and initialized it will append as true. For better performance we have wrapped FileWriter into a BufferedWriter,Similar to wrapping FileInputStream into BufferedReader to read File line by line in Java . Since this is a test program we have not finally block to close connection and also instead of handling Exception we have thrown them to keep the code simple and readable. In production code, you should always close File connection on finally block and ready to handle FileNotFoundException and IOException in Java.
That’s all on how to append text to File in Java. It's rather simple Java program with only one thing to keep in mind, initializing FileWriter with boolean append as true, so that FileWriter writes content at the end of file instead start of the File.
Other Java IO tutorials from Javarevisited Blog