How to append text to a file
Short answer
Pass the CREATE and APPEND options — the file is created if missing, and new text goes to the end:
void main() throws IOException {
Path log = Path.of("app.log");
Files.writeString(log, "first\n", StandardOpenOption.CREATE, StandardOpenOption.APPEND);
Files.writeString(log, "second\n", StandardOpenOption.CREATE, StandardOpenOption.APPEND);
IO.print(Files.readString(log));
}Output:
first
secondA log with timestamps
It is convenient to move the writing into a method:
void log(String message) throws IOException {
String line = LocalTime.of(12, 0, 5) + " " + message + System.lineSeparator();
Files.writeString(Path.of("events.log"), line, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
}
void main() throws IOException {
log("user logged in");
log("order created");
IO.print(Files.readString(Path.of("events.log")));
}Output:
12:00:05 user logged in
12:00:05 order createdThe time is fixed here for the example — in real code use LocalTime.now().
With a BufferedWriter
newBufferedWriter() takes the same options:
void main() throws IOException {
Path file = Path.of("list.txt");
for (String item : List.of("tea", "cake")) {
try (var writer = Files.newBufferedWriter(file, StandardOpenOption.CREATE, StandardOpenOption.APPEND)) {
writer.write(item);
writer.newLine();
}
}
IO.print(Files.readString(file));
}Output:
tea
cakeCommon mistake
Passing only APPEND. If the file does not exist yet, the write fails:
void main() throws IOException {
Files.writeString(Path.of("new.log"), "text", StandardOpenOption.APPEND);
}Output:
Exception in thread "main" java.nio.file.NoSuchFileException: new.logFunctions used in this recipe
- Files.writeString() — Writes a string to a file, creating or overwriting it.