How to append text to a file in Java

In this quick article, I'll show you how to append text to an existing file using Java legacy I/O API as well as non-blocking new I/O API (NIO).

Using Files.write() Method

The simplest and most straightforward way of appending text to an existing file is to use the Files.write() static method. This method is a part of Java's new I/O API (classes in java.nio.* package) and requires Java 7 or higher.

Here is an example that uses Files.write() to append data to a file:

try {
    // append data to a file
    Files.write(Paths.get("output.txt"), "Hey, there!".getBytes(),
            StandardOpenOption.APPEND);

} catch (IOException ex) {
    ex.printStackTrace();
}

The above code will append Hey, there! to a file called output.txt. If the file doesn't exist, it will throw a NoSuchFileException exception. It also doesn't append a new line automatically which is often required when appending to a text file.

If you want to create a new file if it doesn't already exist and also append new line automatically, use another variant of Files.write() as shown below:

try {
    // data to append
    List<String> contents = Arrays.asList("Hey, there!", "What's up?");

    // append data to a file
    Files.write(Paths.get("output.txt"), contents,
            StandardOpenOption.CREATE,
            StandardOpenOption.APPEND);

} catch (IOException ex) {
    ex.printStackTrace();
}

If the file has encoding other than the default character encoding of the operating system, you can specify it like below:

Files.write(Paths.get("output.txt"), contents,
        StandardCharsets.UTF_8,
        StandardOpenOption.CREATE,
        StandardOpenOption.APPEND);

Note: Files.write() is good if you want to append to a file once or a few times only. Because it opens and writes the file every time to the disk, which is a slow operation. For frequent append requests, you should rather BufferedWriter (explained below).

Using BufferedWriter Class

The BufferedWriter class is a part of Java legacy I/O API that can also be used to append text to a file. Here is an example that uses the Files.newBufferedWriter() static method to create a new writer (require Java 8+):

try {
    // create a writer
    BufferedWriter bw = Files.newBufferedWriter(Paths.get("output.txt"),
            StandardOpenOption.APPEND);

    // append text to file
    bw.write("Hey, there!");
    bw.newLine();
    bw.write("What's up?");

    // close the writer
    bw.close();

} catch (IOException ex) {
    ex.printStackTrace();
}

The above code will append text to file. If the file doesn't already exist, it will throw a NoSuchFileException exception. However, you can change it to create a new file if not available with the following:

BufferedWriter bw = Files.newBufferedWriter(Paths.get("output.txt"),
        StandardOpenOption.CREATE,
        StandardOpenOption.APPEND);

To specify a different character encoding, you can do the following:

BufferedWriter bw = Files.newBufferedWriter(Paths.get("output.txt"),
        StandardCharsets.UTF_8,
        StandardOpenOption.CREATE,
        StandardOpenOption.APPEND);

Using FileWriter Class

If you are using Java 7 or below, you can use FileWriter wrapped in a BufferedWriter object to append data to a file as shown below:

try {
    // create a writer
    BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt", true));

    // append text to file
    bw.write("Hey, there!");
    bw.newLine();
    bw.write("What's up?");

    // close the writer
    bw.close();

} catch (IOException ex) {
    ex.printStackTrace();
}

The second argument to the FileWriter constructor will tell it to append data to the file, rather than writing a new file. If the file does not already exist, it will be created.

Further Reading

You may be interested in other Java I/O articles:

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.