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.

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);

Keep in mind that the Files.write() method will overwrite the contents of the file if the file does not exist. If you want to create a new file if it doesn't exist, or if you want to append to the file if it does, you can use the Files.exists() method to check whether the file exists, and then use the appropriate method:

if (Files.exists(file)) {
  Files.write(file, text.getBytes(charset), StandardOpenOption.APPEND);
} else {
  Files.write(file, text.getBytes(charset));
}

This will append the text to the file if it exists, or create a new file and write the text to it if it doesn't.