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
- Start with A line containing A, then end of file
- Do this Read one line
- Result A
Syntax
String line = reader.readLine()
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaCount 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.
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 + "]");
}
}
}
}
[A] [] [B]
The unterminated final line is returned once. A try-with-resources block also closes a reader if processing stops early.
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.
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.
What to watch for
Check for null before using the returned string. Empty lines can be meaningful records.