Lesson 147 min read
File I/O
Read from and write to files like a pro
Why File I/O?
So far, all your data disappears when the program ends — like writing on a whiteboard and erasing it. File I/O (Input/Output) lets you save data to files and read it back later. It's like writing in a notebook instead of on a whiteboard.
Java gives you several tools for working with files:
- File — represents a file or directory path. Doesn't actually read or write, just points to a location.
- Scanner — reads text from files (you already know it from reading user input!).
- FileWriter / PrintWriter — writes text to files.
- BufferedReader — reads files efficiently, line by line, using an internal buffer.
The key rule: always close your files when done. Or better yet, use try-with-resources so Java closes them for you.
Writing to a File
Reading Files
Reading a file is like opening a book — you can read it line by line, word by word, or all at once. The most common approaches:
- Scanner — simple and familiar. Good for small files and parsing different data types.
- BufferedReader — more efficient for large files. Reads chunks of data at once into a buffer (like loading several pages into memory instead of reading one character at a time).
Both should be used with try-with-resources to ensure the file gets closed properly, even if an error occurs.
Reading with Scanner
BufferedReader — Efficient Reading
Note: Always use try-with-resources for file operations. If your program crashes mid-read or mid-write without closing the file, the data might be lost or the file could stay locked. Try-with-resources is your safety net — it always closes the file, even when things go wrong.