Write a Java Program to Append Text to an Existing File

Appending text to an existing file is a common task in Java programming.

In this tutorial, we will discuss how to append text to an existing file using Java.


To append text to an existing file, we need to use the FileWriter class.

The FileWriter class is a subclass of the OutputStreamWriter class, which is used to write characters to a file.

To append text to an existing file, we need to create a FileWriter object with a second argument as true, which tells the FileWriter to append the text to the end of the file instead of overwriting it.

Let’s take a look at the following code example:

import java.io.*;

public class AppendToFile {

    public static void main(String[] args) {

        String filePath = "path/to/your/file.txt";
        String textToAppend = "This is the text to append.";

        try {
            FileWriter fw = new FileWriter(filePath, true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(textToAppend);
            bw.newLine();
            bw.close();
        } catch (IOException e) {
            System.err.println("IOException: " + e.getMessage());
        }
    }
}

In this example, we first define the file path of the file that we want to append the text to.

Then, we define the text that we want to append.

We create a FileWriter object with the file path and a second argument as true to tell the FileWriter to append the text to the file.

We then create a BufferedWriter object with the FileWriter object as an argument to write the text.

We use the write() method to write the text to the file and the newLine() method to add a newline character to the end of the text.

Finally, we close the BufferedWriter object to release the resources.


In conclusion, appending text to an existing file is a simple task in Java using the FileWriter class.

We create a FileWriter object with a second argument as true, which tells the FileWriter to append the text to the end of the file.

We then create a BufferedWriter object to write the text and close the BufferedWriter object to release the resources.