Video in progress
How do you write to the end of a file without erasing its old content?
Pass StandardOpenOption.APPEND (plus CREATE so the file is created if it doesn't exist) to Files.writeString or Files.newBufferedWriter. In the old API it is new FileWriter(file, true).
📖 Answer
By default the write methods truncate the file to zero (TRUNCATE_EXISTING). Many new developers "clear" their log file on every run this way.
Path log = Path.of("audit.log");
Files.writeString(log, "user=42 login\n",
StandardOpenOption.CREATE,
StandardOpenOption.APPEND);
The old style:
try (var w = new FileWriter("audit.log", true)) { // true = append
w.write("user=42 login\n");
}
Note that APPEND alone does not create the file: if it doesn't exist you get NoSuchFileException. That is why it is passed together with CREATE.
In practice you use Logback/Log4j2 instead of writing logs yourself: they take care of rotation, buffering and thread safety.
Sign up to mark studied questions and save your progress.