How to append text to an existing file in Java

I need to append text repeatedly to an existing file in Java. How do I do that?
Last updated:8/14/2015 8:12:27 AM

1 Answers

Mayank Tripathi
Mayank Tripathi

You can use fileWriter with a true for appending.

try
{
    String filename= "MyFile.txt";
    FileWriter fw = new FileWriter(filename,true); //the true will append the new data
    fw.write("add a line\n");//appends the string to the file
    fw.close();
}
catch(IOException ioe)
{
    System.err.println("IOException: " + ioe.getMessage());
}

Answer