Buffered I/O
- Java course
- Advanced
- Lesson 70/82
- 5 min
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 automaticallyThe 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.
Practice 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.
Starter code
import java.nio.file.*;
import java.io.*;
// Write main in BufferedDemo
// Set up with createTempFile and writeString; open BufferedReader with try-with-resources and print readLineSample 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());
}
}
}Expected output
Hello
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When is BufferedReader preferred?
- When reading the whole file at once
- When doing many small reads Correct answer
- Only for binary files
- Only for network I/O
Explanation: BufferedReader speeds up many small reads via a buffer.
2 Match Buffered I/O concepts
| Term | Meaning |
|---|---|
BufferedReader |
Buffered reading |
BufferedWriter |
Buffered writing |
newBufferedReader |
Opens on Files |
lines() |
Gives a line stream |
3 Complete the BufferedReader call
try (____ r = Files.newBufferedReader(p)) {
String line = r.readLine();
}
try (BufferedReader r = Files.newBufferedReader(p)) {
String line = r.readLine();
}
Explanation: Files.newBufferedReader returns a BufferedReader.