CodeBlanks Logo Icon CodeBlanks

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.

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

Main.java
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 readLine

Sample solution

Main.java
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

Question
try (____ r = Files.newBufferedReader(p)) {
    String line = r.readLine();
}
Answer
try (BufferedReader r = Files.newBufferedReader(p)) {
    String line = r.readLine();
}

Explanation: Files.newBufferedReader returns a BufferedReader.

All lessons in Advanced