Java Append to File Example

In this source code example, we show you how to append a string to an existing file in Java.

We use write() method from java.nio.file.Files class to append data to a file.

Java Append to File Example

This example appends data with Files.
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class JavaAppendFileFiles {
    public static void main(String[] args) throws IOException {
        String fileName = "src/main/resources/sample.txt";
        byte[] tb = "appending some string\n".getBytes();
        Files.write(Paths.get(fileName), tb, StandardOpenOption.APPEND);
The third parameter of Files.write() tells how the file was opened for writing. With the StandardOpenOption.APPEND, the file was opened for appending.
Files.write(Paths.get(fileName), tb, StandardOpenOption.APPEND);


Free Spring Boot Tutorial - 5 Hours Full Course

Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course