Java
Buffered I/O
Learn efficient I/O with BufferedInputStream and BufferedOutputStream.
Buffered I/O
BufferedReader and BufferedWriter use a buffer instead of going to disk on every read/write. This greatly improves performance for many small operations.
try (BufferedReader r = Files.newBufferedReader(p)) {
String line = r.readLine();
}
try-with-resources closes the stream automatically. This prevents resource leaks. For line-by-line reading, the lines() stream can also be used; it fits Stream API processing.
try-with-resources
In Java 7+, resources opened with try-with-resources are closed automatically. This prevents file and stream leaks.
try (BufferedReader r = Files.newBufferedReader(p)) {
// use r
} // r.close() is called automatically
The resource must implement AutoCloseable. Multiple resources are separated by semicolons. This is the standard way of error-free resource management and is essentially mandatory in production code.
Exercise Read a line with BufferedReader
Write main in a BufferedDemo class; create a temp file with Files.createTempFile("b", ".txt"), write Files.writeString(p, "Hello"). Inside a try (BufferedReader r = Files.newBufferedReader(p)) block, read the first line with r.readLine() and print it with System.out.println.
Show example solution
import java.nio.file.*;
import java.io.*;
class BufferedDemo {
public static void main(String[] args) throws Exception {
Path p = Files.createTempFile("b", ".txt");
Files.writeString(p, "Hello");
try (BufferedReader r = Files.newBufferedReader(p)) {
System.out.println(r.readLine());
}
}
}
Test yourself
-
When is BufferedReader preferred?
- When reading the whole file at once
- When doing many small reads
- Only for binary files
- Only for network I/O
Show answer
When doing many small reads — BufferedReader speeds up many small reads via a buffer.
-
Match Buffered I/O concepts
- BufferedReader
- Buffered reading
- BufferedWriter
- Buffered writing
- newBufferedReader
- Opens on Files
- lines()
- Gives a line stream
-
Complete the BufferedReader call
try (____ r = Files.newBufferedReader(p)) {
String line = r.readLine();
}
Show answer
try (BufferedReader r = Files.newBufferedReader(p)) {
String line = r.readLine();
}
Next lesson: Channels