SwadhyAI Notes

All Java notes

Java BufferedReader Reference

›Short versionOpen if you only have a minute.
  • BufferedReader reads characters through a buffer, usually wrapped around a FileReader or an InputStreamReader.
  • readLine returns the line without its line break, or null at the end of the file.
  • An empty string from readLine is a blank line. It is not the end of the file.
  • read(char[]) returns how many characters were stored, or -1 at the end. Use that count.
  • ready is not an end-of-file test. lines() still needs the reader closed by the caller.
  • FileReader uses the platform charset. Wrap an InputStreamReader with StandardCharsets.UTF_8 when the file is UTF-8.

BufferedReader reads characters through an internal buffer and is commonly used for fast line-by-line text input.

Methods

APIParametersReturnsBehaviorWatch for
new BufferedReader(Reader in)Reader source, optional buffer size overload.BufferedReader.Adds buffering around character input.The wrapped reader still determines character decoding.
readLine()None.Line without terminator, or null at EOF.Reads until line break or EOF.Line separator characters are not included.
read(char[] cbuf)Character buffer.Characters read, or -1 at EOF.Fills part or all of the buffer.Use the returned count, not the whole buffer blindly.
ready()None.boolean.Indicates whether reading may avoid blocking.Not a reliable EOF test.
lines()None.Stream<String>.Lazily streams lines from the reader.The reader must still be closed.
close()None.void.Closes the reader and wrapped source.Further reads throw IOException.

Which call fits

OptionBest forTradeoff
BufferedReaderFast text line reading.Manual parsing for numbers and tokens.
ScannerConvenient token parsing.Slower and easier to misuse with newlines.
Files.readAllLines()Small files loaded completely.Consumes memory for all lines at once.

Examples

Read all lines

java
try (BufferedReader reader = new BufferedReader(new FileReader("notes.txt"))) {
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
}

Use an explicit charset

java
try (BufferedReader reader = new BufferedReader(
        new InputStreamReader(new FileInputStream("notes.txt"), StandardCharsets.UTF_8))) {
    System.out.println(reader.readLine());
}

The file is hello, then a blank line, then world. What are the three values readLine returns?

"hello", then "", then "world". A fourth call returns null. The blank line is a real line whose content is empty. The line break itself is not included in any of the strings.