Append Text to a File in Java
Problem
Opening a file in append mode positions writing at the end of the existing content, instead of truncating the file to empty first.
Given a log file with one entry, add two more entries to the end and print the whole file.
Java Program
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
public class AppendToFile {
public static void main(String[] args) throws IOException {
Path log = Paths.get("app.log");
Files.write(log, Arrays.asList("09:00 server started"));
try (PrintWriter out = new PrintWriter(new FileWriter(log.toFile(), true))) { // true = append mode
out.println("09:05 user logged in");
out.println("09:12 report exported");
}
Files.readAllLines(log).forEach(System.out::println);
Files.delete(log);
}
}Output
Core Logic
The second constructor argument of FileWriter switches it from overwrite mode to append mode.
- 1
Files.writecreatesapp.logwith a single starting entry. - 2
new FileWriter(log.toFile(), true)opens it for appending. - 3Wrapping it in a
PrintWriterallows convenientprintlncalls. - 4Reading the file back shows the original line followed by the two new ones.
09:00 server started line survives, and the two new entries appear after it.Key Point: new FileWriter(file) without true silently wipes the file — one missing argument is a common way to lose log data.
Key Concepts
Approach 2: Using StandardOpenOption.APPEND
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
public class AppendToFileNio {
public static void main(String[] args) throws IOException {
Path log = Paths.get("app.log");
Files.write(log, Arrays.asList("09:00 server started"));
Files.write(log, Arrays.asList("09:05 user logged in"),
StandardOpenOption.APPEND); // add to the end instead of replacing
Files.readAllLines(log).forEach(System.out::println);
Files.delete(log);
}
}
Output
Core Logic
With NIO, the open options passed to Files.write decide whether existing content is kept.
- 1
Files.write(log, lines, StandardOpenOption.APPEND)adds the lines to the end. - 2Without options,
Files.writecreates or truncates the file. - 3Adding
StandardOpenOption.CREATEas well would create the file if it doesn't exist yet.
Key Point: APPEND alone fails with NoSuchFileException if the file is missing — combine it with CREATE for log files that may not exist yet.
Key Concepts
Interview Questions
How do you append on a new line?
Write a line separator yourself — println with a PrintWriter, or System.lineSeparator() — because appending doesn't add a newline automatically.
Is appending safe when several programs write the same file?
Not reliably. Writes from different processes can interleave; logging frameworks or file locks are used when that matters.