Library contents

Java BufferedReader.readLine

A buffered reader is useful when each line represents one record. readLine returns an empty string for a blank line and null when the input ends.

A simple example

BufferedReader.readLine

  1. Start with A line containing A, then end of file
  2. Do this Read one line
  3. Result A
Reading one line yields its text. A subsequent read reaches the end.

Syntax

Java syntax
String line = reader.readLine()
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Count blank lines and detect end of input

A line-based import may include a blank record or a last record without a terminating newline. Distinguish a legitimate line from the end of the input so the import keeps the right number of rows.

First output line[A]
Main.java
import java.io.BufferedReader;
import java.io.StringReader;

class Main {
    public static void main(String[] args) throws Exception {
        try (var reader = new BufferedReader(new StringReader("A\r\n\nB"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println("[" + line + "]");
            }
        }
    }
}
Output
[A]
[]
[B]

The unterminated final line is returned once. A try-with-resources block also closes a reader if processing stops early.

Advertisements

Read a studio sign-in sheet

A rehearsal has two names with a reserved blank row between them. Count every saved line, including an empty line between two entries. The end of input adds no extra line.

GivenAda / blank / Kim
Worked result3

Read a single shift instruction

A shop closes after recording one instruction without a final newline. Count every saved line, including an empty line between two entries. The end of input adds no extra line.

GivenLock door + EOF
Worked result1

What to watch for

Check for null before using the returned string. Empty lines can be meaningful records.

Documentation for BufferedReader.readLine