8.3 Writing, Appending, and Resource Management
Writing files is not just "put text somewhere." You need to decide whether to create a new file, overwrite old content, append to the end, create missing folders, and close resources reliably.
Writing Small Text Files
For short text, Files.writeString() is the simplest option.
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class WriteStringDemo {
public static void main(String[] args) throws IOException {
Path path = Path.of("study_log.txt");
String text = String.join(System.lineSeparator(),
"Today I learned Path.",
"Files.writeString writes text.",
"UTF-8 keeps text predictable."
);
Files.writeString(path, text + System.lineSeparator(), StandardCharsets.UTF_8);
}
}By default, Files.writeString() creates the file if needed and replaces the content if the file already exists. That replacement behavior is useful when you are producing a fresh report, but dangerous if you meant to preserve old data.
Appending with StandardOpenOption
StandardOpenOption lets you say what should happen when writing.
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
public class AppendDemo {
public static void main(String[] args) throws IOException {
Path path = Path.of("events.log");
Files.writeString(
path,
"Program started" + System.lineSeparator(),
StandardCharsets.UTF_8,
StandardOpenOption.CREATE,
StandardOpenOption.APPEND
);
}
}Common options:
CREATE: create the file if it does not exist.CREATE_NEW: create the file only if it does not exist; fail if it already exists.TRUNCATE_EXISTING: clear old content before writing.APPEND: write new content at the end.
Options matter because file output can destroy data. Always make the overwrite-or-append decision visible in your code.
BufferedWriter and PrintWriter
For many small writes, BufferedWriter is efficient and explicit.
try (BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
writer.write("Name,Score");
writer.newLine();
writer.write("Alice,92");
writer.newLine();
}PrintWriter is useful when you want print, println, and printf style methods.
try (PrintWriter writer = new PrintWriter(Files.newBufferedWriter(path, StandardCharsets.UTF_8))) {
writer.println("Name,Score");
writer.printf("%s,%d%n", "Alice", 92);
}The bigger lesson is resource lifetime. Writers usually buffer data before sending it to disk. Closing the writer flushes remaining data. Try-with-resources is the cleanest habit because it handles closing even when an exception interrupts the block.