Write Files
In short: Writing data into a file — e.g. with FileWriter, BufferedWriter, or the static method Files.write(...).
In more detail: Without append mode (new FileWriter(file, true)), every reopen completely overwrites the existing file. BufferedWriter buffers write access in memory and thus reduces expensive individual disk accesses — should be closed after use (ideally via try-with-resources), so buffered data lands safely.
In Depth
// Simple, but every .write() call can be an expensive individual disk access:
try (FileWriter fw = new FileWriter("note.txt")) {
fw.write("First line\n");
fw.write("Second line\n");
} catch (IOException e) {
e.printStackTrace();
}
// Buffered, more efficient for many individual write operations:
try (BufferedWriter bw = new BufferedWriter(new FileWriter("note.txt", true))) { // true = append
bw.write("Appended line");
bw.newLine();
} catch (IOException e) {
e.printStackTrace();
}
// Compact for simple cases (since Java 7):
Files.writeString(Path.of("note.txt"), "Entire content at once");Without the second true parameter in the FileWriter constructor, every reopen overwrites the file completely from scratch — if content should instead be appended to existing content, that has to be explicitly requested via this append mode. BufferedWriter wraps a FileWriter and first collects write accesses in working memory, instead of accessing the disk directly on every single .write() call — this significantly reduces the number of expensive I/O operations, especially for many small write operations in a loop.
Important: buffered data only GUARANTEED lands on disk once the writer is closed (or .flush() is explicitly called) — if the program terminates beforehand (e.g. due to a crash), unwritten buffer content can be lost. This is exactly why writing almost always belongs in a try-with-resources, which guarantees closing (and thus the final flush) even on an exception. For simple cases with no streaming, the static utility method Files.writeString(...) (or Files.write(...) for byte arrays) has offered an even more compact alternative since Java 7, which itself internally handles correct opening/closing.
See also: Files, BufferedWriter, Create Files