Write to a File in Java
Problem
Writing a file means opening an output stream to it, sending characters, and closing it; a BufferedWriter collects characters in memory and writes them in larger, more efficient chunks.
Create a text file containing three to-do items, one per line, then read the file back to show what was written.
Java Program
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class WriteToFile {
public static void main(String[] args) throws IOException {
Path file = Paths.get("notes.txt");
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file.toFile()))) { // closed automatically
writer.write("Buy milk");
writer.newLine(); // the platform's line separator
writer.write("Call the bank");
writer.newLine();
writer.write("Finish the report");
}
System.out.println("Wrote " + Files.readAllLines(file).size() + " lines to " + file);
System.out.println("File contents:");
for (String line : Files.readAllLines(file)) {
System.out.println(" " + line);
}
Files.delete(file); // tidy up the demo file
}
}Output
Core Logic
A BufferedWriter wrapped around a FileWriter handles the writing, and try-with-resources guarantees the file is flushed and closed.
- 1
new FileWriter(file.toFile())createsnotes.txt, or empties it if it already exists. - 2
writer.write(...)sends each item, andnewLine()adds the operating system's line separator. - 3Leaving the
tryblock closes the writer, which flushes any buffered text to disk. - 4
Files.readAllLinesreads the file back to prove the content arrived, then the demo file is deleted.
write calls and two newLine calls produce a three-line file.Key Point: If a writer is never closed, the last buffered characters may never reach the disk — which is why try-with-resources is the standard pattern.
Key Concepts
Approach 2: Using Files.writeString() and Files.write()
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
public class WriteToFileNio {
public static void main(String[] args) throws IOException {
Path file = Paths.get("notes.txt");
Files.writeString(file, "A single string, written in one call\n"); // Java 11+
System.out.print("After writeString: " + Files.readString(file));
List<String> lines = Arrays.asList("line one", "line two");
Files.write(file, lines); // replaces the old contents, one element per line
System.out.println("After write(lines): " + Files.readAllLines(file));
Files.delete(file);
}
}
Output
Core Logic
The java.nio.file.Files helpers open, write and close the file in a single call.
- 1
Files.writeString(file, text)(Java 11+) writes one string in UTF-8. - 2
Files.write(file, lines)writes a list, one element per line, replacing the previous contents. - 3
Files.readStringandFiles.readAllLinesread the results back.
line one and line two.Key Point: These helpers are perfect for small files; use a BufferedWriter when writing large amounts of data incrementally.
Key Concepts
Interview Questions
Does FileWriter overwrite an existing file?
Yes, by default it truncates the file. Pass true as the second argument to append instead.
Why use BufferedWriter rather than FileWriter alone?
Buffering collects characters in memory and writes them in larger chunks, which is much faster than many small writes.