Skip to lesson

BufferedReader and BufferedWriter

A BufferedReader reads a text file line by line and a BufferedWriter writes one piece by piece, both through a block of memory called a buffer. They handle files of any size and give you full control: line numbers, early stops and writing as you go.

Files.newBufferedReader and newBufferedWriter with a charset

Buffering collects data in memory and reads or writes it in large chunks, so a program makes far fewer slow calls to the disk.

A buffer is a block of memory that collects characters so the file is read or written in big chunks instead of one character at a time. Files.newBufferedReader(path, charset) opens a file for reading through a buffer; Files.newBufferedWriter(path, charset) opens one for writing.

Example 1 · A buffered writer and a buffered reader

HostelRoomsDemo.javaJava
import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;
public class HostelRoomsDemo {    public static void main(String[] args) throws IOException {        Path file = Path.of("hostel.txt");
        try (BufferedWriter out = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {            out.write("Room 101: Asha");            out.newLine();            out.write("Room 102: Ravi");            out.newLine();        }
        try (BufferedReader in = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {            System.out.println("First line: " + in.readLine());            System.out.println("Second line: " + in.readLine());            System.out.println("Third line: " + in.readLine());        }
        Files.delete(file);    }}
Output
First line: Room 101: Asha
Second line: Room 102: Ravi
Third line: null

What this code does

  • write adds text to the writer's buffer and newLine adds a line break; the try-with-resources block closes the writer, which pushes everything to the file.
  • Each readLine returns the next line without its line break. There is no third line, so the third call returns null.

Both default to UTF-8 when you leave the charset out, but passing StandardCharsets.UTF_8 makes it clear. The writer takes the same open options as Files.writeString: by default it creates or replaces the file, and CREATE, APPEND adds to the end. Open both in try-with-resources.

The readLine loop and null at the end

readLine() returns the next line of the file without its line break, or null when there are no more lines. It understands \n, \r\n and \r, so Windows files are safe.

Example 2 · The readLine loop: add up hostel fees

FeeLoopDemo.javaJava
import java.io.BufferedReader;import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;
public class FeeLoopDemo {    public static void main(String[] args) throws IOException {        Path file = Path.of("fees.csv");        Files.writeString(file, "Asha,45000\nRavi,38000\nMeena,52000\n");
        int total = 0;        int students = 0;        try (BufferedReader in = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {            String line;            while ((line = in.readLine()) != null) {                String[] parts = line.split(",");                total += Integer.parseInt(parts[1]);                students++;            }        }        System.out.println("Students: " + students);        System.out.println("Total fees: Rs " + total);
        Files.delete(file);    }}
Output
Students: 3
Total fees: Rs 135000

What this code does

  • (line = in.readLine()) != null reads one line into line and checks it in the same step. The loop ends when readLine returns null at the end of the file.
  • Only the current line is in memory, so the same loop works for a file of any size.

The standard loop reads a line into a variable and checks it in one step: while ((line = in.readLine()) != null) { ... }. An empty line in the file comes back as "", not null, so the loop does not stop at blank lines.

Trace the code

Watch readLine reach null

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
public class ReadLoop {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new StringReader("Asha\nRavi\n"));
int count = 0;
String line;
while ((line = in.readLine()) != null) {
count++;
System.out.println(count + ": " + line);
}
System.out.println("Lines: " + count);
}
}

Variables

None yet.

Output

(nothing printed yet)

Line 7The BufferedReader wraps a StringReader holding two lines. Nothing has been read yet.

Step 1 of 10

newLine, flush and close

write(text) adds text to the writer's buffer and newLine() adds the platform line separator. Nothing is guaranteed to be in the file yet: the buffer is written out when it is full, when you call flush(), or when you call close().

Example 3 · Mistake: data waits in the buffer until flush or close

FlushDemo.javaJava
import java.io.BufferedWriter;import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;
public class FlushDemo {    public static void main(String[] args) throws IOException {        Path file = Path.of("notes.txt");        // No try-with-resources here, only to show the buffer step by step        BufferedWriter out = Files.newBufferedWriter(file, StandardCharsets.UTF_8);
        out.write("Lab record due Friday");        System.out.println("After write: " + Files.size(file) + " bytes");
        out.flush();        System.out.println("After flush: " + Files.size(file) + " bytes");
        out.write(" - bring the printout");        out.close();        System.out.println("After close: " + Files.size(file) + " bytes");
        Files.delete(file);    }}
Output
After write: 0 bytes
After flush: 21 bytes
After close: 42 bytes

What this code does

  • After write, the 21 characters are only in the buffer in memory; the file on disk is still empty. If the program crashed now, the text would be lost.
  • flush pushes the buffer to the file and keeps the writer open. close flushes the rest and then closes the file. try-with-resources calls close for you, even when an exception is thrown.

flush pushes the buffer to the file and keeps the writer open. close flushes and then releases the file. A writer that is never closed can leave a file empty or cut off at the end, which is why try-with-resources matters even more for writers than for readers.

newLine follows the platform like System.lineSeparator(). When a file must use \n everywhere, write "\n" yourself.

Keeping a line number while reading

A line number turns "the file has a bad row" into "line 2: marks abc is not a number". Keep an int counter and add 1 at the top of the loop, before any continue, so blank and skipped lines are counted too.

Example 4 · Keeping a line number while reading

MarksValidatorDemo.javaJava
import java.io.BufferedReader;import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;
public class MarksValidatorDemo {    public static void main(String[] args) throws IOException {        Path file = Path.of("marks.csv");        Files.writeString(file, "Asha,86\nRavi,abc\n\nMeena,91\nKiran\n");
        int lineNo = 0;        int valid = 0;        int total = 0;        try (BufferedReader in = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {            String line;            while ((line = in.readLine()) != null) {                lineNo++;                if (line.isBlank()) {                    continue;                }                String[] parts = line.split(",");                if (parts.length != 2) {                    System.out.println("Line " + lineNo + ": expected name,marks but got \"" + line + "\"");                    continue;                }                try {                    total += Integer.parseInt(parts[1]);                    valid++;                } catch (NumberFormatException e) {                    System.out.println("Line " + lineNo + ": marks \"" + parts[1] + "\" is not a number");                }            }        }        System.out.println("Valid rows: " + valid + ", total marks: " + total);
        Files.delete(file);    }}
Output
Line 2: marks "abc" is not a number
Line 5: expected name,marks but got "Kiran"
Valid rows: 2, total marks: 177

What this code does

  • lineNo++ runs for every line, blank ones included, so the numbers match what the user sees in a text editor.
  • Each bad row is reported with its line number and the program carries on. Someone fixing a 10,000-line file can go straight to line 2 and line 5.

The same loop can skip a header (lineNo == 1), report every bad row and carry on, and write good rows to a second file through a BufferedWriter declared in the same try.

Example 5 · Reader and writer together: write the absentee list

AbsenteesDemo.javaJava
import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;
public class AbsenteesDemo {    public static void main(String[] args) throws IOException {        Path input = Path.of("attendance.csv");        Path output = Path.of("absentees.txt");        Files.writeString(input, "roll,name,status\n101,Asha,P\n102,Ravi,A\n103,Meena,P\n104,Kiran,A\n");
        int lineNo = 0;        int written = 0;        try (BufferedReader reader = Files.newBufferedReader(input, StandardCharsets.UTF_8);             BufferedWriter writer = Files.newBufferedWriter(output, StandardCharsets.UTF_8)) {            String line;            while ((line = reader.readLine()) != null) {                lineNo++;                if (lineNo == 1) {                    continue; // header                }                String[] parts = line.split(",");                if (parts[2].equals("A")) {                    writer.write(parts[0] + " " + parts[1] + " (line " + lineNo + ")");                    writer.newLine();                    written++;                }            }        }        System.out.println("Read " + lineNo + " lines, wrote " + written + " absentees");        System.out.print(Files.readString(output));
        Files.delete(input);        Files.delete(output);    }}
Output
Read 5 lines, wrote 2 absentees
102 Ravi (line 3)
104 Kiran (line 5)

What this code does

  • Both resources are declared in one try, separated by a semicolon. They are closed in reverse order, writer first, so the output is flushed before the program reads it back.
  • This streams any size of attendance file: one line in, at most one line out, and a counter for the line numbers.

Next step

Check your understanding

10 quick questions