W3docs

How to append text to an existing file in Java?

To append text to the end of an existing file in Java, you can use the Files.write() method from the java.nio.file package. This method allows you to write a sequence of characters to a file in a single operation.

Tags

To append text to the end of an existing file in Java, you can use the Files.write() method from the java.nio.file package. This method allows you to write a sequence of characters to a file in a single operation.

Here's an example of how to use the Files.write() method to append text to a file:


import java.nio.file.*;
import java.nio.charset.*;

Path file = Paths.get("filename.txt");
String text = "This is the text to be appended to the file.";
Charset charset = StandardCharsets.UTF_8;

Files.write(file, text.getBytes(charset), StandardOpenOption.APPEND);

In this example, we're using the StandardOpenOption.APPEND option to open the file in append mode, which allows us to write to the end of the file rather than overwriting its contents.

The Files.write() method can write any Iterable object, such as a List or an array, to a file. For example, you can use it to write the lines of a List<String> to a file like this:


List<String> lines = Arrays.asList("line 1", "line 2", "line 3");
Files.write(file, lines, charset, StandardOpenOption.APPEND);

Note that Files.write() throws a NoSuchFileException if the target file does not exist. To safely append to an existing file or create a new one if it's missing, combine StandardOpenOption.CREATE with StandardOpenOption.APPEND:


Files.write(file, text.getBytes(charset), StandardOpenOption.CREATE, StandardOpenOption.APPEND);

For Java 11 and later, you can use Files.writeString() to avoid manual charset conversion:


Files.writeString(file, text, StandardOpenOption.CREATE, StandardOpenOption.APPEND);

This approach automatically creates the file if it doesn't exist and appends the text if it does.