Buffered I/O
Reading and writing one character at a time is simple but inefficient โ each small read/write hits the disk, which is slow.
Buffered I/O fixes this by adding a memory buffer:
Instead of reading one character, it reads a chunk into memory.
Instead of writing each character instantly, it collects them and writes in bigger blocks.
This reduces disk I/O calls, which speeds things up a lot, especially for large files.
Key classes:
BufferedReader
wraps FileReader
.
BufferedWriter
wraps FileWriter
.
These add powerful extra methods too:
BufferedReader.readLine()
reads whole lines at a time.
BufferedWriter.newLine()
safely adds platform-specific newlines.
Below is an upgraded lab โ same as before, but using Buffered
classes for faster, cleaner code.
โ How this works:
BufferedWriter
wraps FileWriter
, adding newLine()
for portable line breaks.
BufferedReader
makes readLine()
possible โ very handy for parsing config files, logs, CSVs.
Always close buffered streams! Unflushed data can be lost if you skip .close()
.
Always use try-catch
โ file operations often fail (file missing, no permission, disk full).
Use finally
or try-with-resources
(try(...) {}
) to ensure streams are closed automatically.
Prefer BufferedReader
/BufferedWriter
for all but the tiniest text files.
For binary data (images, PDFs), switch to FileInputStream
and FileOutputStream
+ BufferedInputStream
/ BufferedOutputStream
.