How to Append Text to a File in Java

In a previous post, I wrote about writing text to a new file (or overwriting an existing one). The following code is similar except this time it appends text to the end of an existing one. The path will use the current path where Java is executing unless you specify a directory in filePath (e.g. C:\\Temp\\JavaTest.txt).

import java.io.*;
 
...
public static void AppendTextToFile(String filePath, String text) throws Exception
{
    FileWriter out = new FileWriter(filePath, true);
    out.write(text);
    out.close();
}

Leave a Reply