BufferedReader and BufferedWriter

Buffered Streams

BufferedWriter and BufferedReader read and write in chunks, which is efficient for writing many small pieces or reading line by line with full control. Get them from Files.newBufferedWriter / Files.newBufferedReader.

Example

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
    public static void main(String[] args) throws IOException {
        Path csv = Files.createTempFile("marks", ".csv");
        try {
            try (BufferedWriter w = Files.newBufferedWriter(csv)) {
                w.write("name,marks");
                w.newLine();
                String[][] rows = { { "Asha", "88" }, { "Ravi", "72" }, { "Meena", "95" } };
                for (String[] r : rows) {
                    w.write(r[0] + "," + r[1]);
                    w.newLine();
                }
            }                                         // closed and flushed here

            int total = 0, count = 0;
            try (BufferedReader r = Files.newBufferedReader(csv)) {
                String header = r.readLine();          // skip header
                System.out.println("Header: " + header);
                String line;
                while ((line = r.readLine()) != null) {
                    String[] parts = line.split(",");
                    total += Integer.parseInt(parts[1]);
                    count++;
                    System.out.println(parts[0] + " scored " + parts[1]);
                }
            }
            System.out.println("Average: " + (total / count));
        } finally {
            Files.deleteIfExists(csv);
        }
    }
}

Output

Header: name,marks
Asha scored 88
Ravi scored 72
Meena scored 95
Average: 85

Which API to Use

NeedUse
Small file, all at onceFiles.readString / Files.writeString
List of lines (small/medium file)Files.readAllLines / Files.write(path, lines)
Huge file, filter or countFiles.lines in try-with-resources
Many writes, line by line controlFiles.newBufferedWriter / newBufferedReader
Binary data (images, PDFs)Files.readAllBytes, Files.newInputStream
Reading user input from the consoleScanner(System.in) or BufferedReader(new InputStreamReader(System.in))

Practice

Exercise: Write a method long countWords(Path file) that returns the number of words in a text file. Use Files.lines and close the stream properly.

Show answer
static long countWords(Path file) throws IOException {
    try (Stream<String> lines = Files.lines(file)) {
        return lines.map(String::strip)
                    .filter(l -> !l.isEmpty())
                    .mapToLong(l -> l.split(" +").length)
                    .sum();
    }
}