Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

BufferedReader

Reads text line by line with buffering — the classic way to process large files.

Available since: Java 1.1

Syntax

public class BufferedReader extends Reader

Examples

Reading a file line by line with readLine():

void main() throws IOException {
    Path file = Path.of("todo.txt");
    Files.writeString(file, "wash dishes\nwrite report\n");
 
    try (BufferedReader reader = Files.newBufferedReader(file)) {
        String line;
        while ((line = reader.readLine()) != null) {
            IO.println("- " + line);
        }
    }
    Files.delete(file);
}

Output:

- wash dishes
- write report

Writing with BufferedWriter:

void main() throws IOException {
    Path file = Path.of("out.txt");
    try (BufferedWriter writer = Files.newBufferedWriter(file)) {
        writer.write("line 1");
        writer.newLine();
        writer.write("line 2");
    }
    IO.println(Files.readAllLines(file));
    Files.delete(file);
}

Output:

[line 1, line 2]

Notes

readLine() returns null when the file ends. Create a reader with Files.newBufferedReader(path) — it uses UTF-8. The new BufferedReader(new FileReader(...)) pattern from old tutorials used the system encoding before Java 18. For simple tasks Files.readAllLines() or Files.lines() is shorter.

See also

  • Files.lines() — Reads a file lazily as a stream of lines, without loading it into memory.
  • Scanner — Reads input piece by piece: whole lines (nextLine) or separate words and numbers.
  • Files.readAllLines() — Reads a text file into a list of lines.
  • try / catch / finally — Catches exceptions; finally always runs, and try-with-resources closes resources for you.

Related recipes

In the tutorial

  • Reading and writing files — Reading and writing text files in Java — Files.writeString, readString, readAllLines, write, appending to the end, Files.lines and buffered streams.

Thanks for reading!

Donate to the site — we work hard for you.