Reading and Writing Files in Java
Java offers several layers of API for reading and writing files, from low-level byte streams up to convenient, modern one-line helpers. Files.readString(path) and Files.writeString(path, text), both from java.nio.file added in Java 11, cover the common case of reading or writing an entire text file's contents in a single call; for line-by-line processing of larger files, BufferedReader wrapped around a FileReader reads one line at a time without loading the whole file into memory at once.
Writing a file with FileWriter defaults to overwriting any existing file completely — passing true as a second constructor argument switches it to append mode instead, adding new content to the end rather than replacing what's already there. Any of these file operations can throw IOException, a checked exception, since a file read or write can genuinely fail for external reasons like a missing file or a full disk.
Files.readString(path)
Reads an entire text file's contents into one String, in a single call, since Java 11.
Files.writeString(path, text)
Writes a String's contents to a file in a single call, also since Java 11.
BufferedReader for line-by-line reading
Processes a file one line at a time, without loading the whole thing into memory at once.
FileWriter's overwrite-by-default behavior
Creates or completely replaces a file's contents unless append mode is explicitly requested.
IOException
A checked exception nearly every file operation can throw, since reads and writes can fail for reasons outside the program's control.
import java.nio.file.Files;import java.nio.file.Path; public class FileWriteReadDemo { public static void main(String[] args) throws Exception { Path file = Path.of("notes.txt"); Files.writeString(file, "Hello, file!"); String content = Files.readString(file); System.out.println("Read back: " + content); }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.