Lesson 2 of 8
BufferedReader & BufferedWriter - Line-by-Line I/O
For large files, readAllLines() loads everything into memory - bad for gigabyte files. BufferedReader reads line-by-line with buffering, while BufferedWriter provides efficient writing. Always use try-with-resources to ensure files are closed properly.
Buffered I/O for Large Files
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
public class BufferedIODemo {
// Read large file line by line - O(1) memory (not O(n))
public static long countBooks(Path file) throws IOException {
long count = 0;
try (BufferedReader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
String line;
while ((line = reader.readLine()) != null) {
if (!line.isBlank()) count++; // skip empty lines
}
} // reader.close() called automatically
return count;
}
// Stream of lines - lazy, memory-efficient (Java 8+)
public static void processLargeFile(Path file) throws IOException {
try (var lines = Files.lines(file, StandardCharsets.UTF_8)) {
lines.filter(l -> !l.isBlank())
.map(String::trim)
.distinct()
.sorted()
.limit(100) // take first 100 distinct sorted lines
.forEach(System.out::println);
} // stream closed = BufferedReader closed
}
// Write with BufferedWriter
public static void writeReport(Path output, Iterable<String> lines) throws IOException {
try (BufferedWriter writer = Files.newBufferedWriter(output, StandardCharsets.UTF_8,
StandardOpenOption.CREATE,
StandardOpenOption.TRUNCATE_EXISTING)) {
for (String line : lines) {
writer.write(line);
writer.newLine(); // OS-correct line separator
}
}
}
// PrintWriter - handy for printf-style writing
public static void writeFormattedReport(Path output, List<Book> books) throws IOException {
try (PrintWriter pw = new PrintWriter(Files.newBufferedWriter(output, StandardCharsets.UTF_8))) {
pw.println("=== LIBRARY CATALOG REPORT ===");
pw.printf("%-30s %-20s %8s%n", "Title", "Author", "Price");
pw.println("-".repeat(62));
for (Book book : books) {
pw.printf("%-30s %-20s $%7.2f%n",
book.getTitle(), book.getAuthor(), book.getPrice());
}
}
}
public static void main(String[] args) throws IOException {
Path catalog = Path.of("catalog.csv");
System.out.println("Book count: " + countBooks(catalog));
processLargeFile(catalog);
}
}Quick Quiz
Tip
Tip
Practice BufferedReader BufferedWriter LinebyLine IO in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for BufferedReader & BufferedWriter - Line-by-Line I/O
Practice Task
Note
Practice Task - (1) Write a working example of BufferedReader BufferedWriter LinebyLine IO from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with BufferedReader BufferedWriter LinebyLine IO is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.
Finished this lesson?