Java

BufferedReader / BufferedWriter

admin by @admin ADMIN
8m ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
For large files or line-oriented protocols, wrap a Reader/Writer in `Buffered*`. Reduces per-call overhead from many small reads to fewer large ones. Always close with try-with-resources.
Java
Raw
import java.io.*;
import java.nio.file.*;

class Demo {
    void example() throws IOException {
        // Stream lines from a multi-GB log file with constant memory
        try (BufferedReader r = Files.newBufferedReader(Path.of("/var/log/big.log"))) {
            String line;
            while ((line = r.readLine()) != null) {
                if (line.contains("ERROR")) System.out.println(line);
            }
        }

        // Same idea with Files.lines() — stream API style
        try (var lines = Files.lines(Path.of("/var/log/big.log"))) {
            long errors = lines.filter(l -> l.contains("ERROR")).count();
            System.out.println("errors: " + errors);
        }

        // Write lines efficiently
        try (BufferedWriter w = Files.newBufferedWriter(Path.of("out.log"))) {
            for (int i = 0; i < 10_000; i++) {
                w.write("line " + i);
                w.newLine();
            }
        }
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.