Read Files
In short: Reading a file’s content — e.g. line by line with BufferedReader or all at once with Files.readAllLines(path).
In more detail: Reading line by line with BufferedReader.readLine() (returns null once the end of the file is reached) is suitable for large files that shouldn’t fit entirely into memory. Files.readAllLines(...) is more compact, but loads the entire file at once.
In Depth
// Variant 1: line by line, memory-efficient for large files
try (BufferedReader br = new BufferedReader(new FileReader("large.txt"))) {
String line;
while ((line = br.readLine()) != null) {
// process each line individually, without holding the whole file in memory
}
}
// Variant 2: everything at once, compact for small/medium files
List<String> allLines = Files.readAllLines(Path.of("small.txt"));
String fullText = Files.readString(Path.of("small.txt")); // since Java 11
// Variant 3: process as a stream, without loading everything at once
try (Stream<String> lines = Files.lines(Path.of("large.txt"))) {
long errorCount = lines.filter(l -> l.contains("ERROR")).count();
}The choice between the three variants depends almost entirely on file size: Files.readAllLines()/readString() are the most compact to write, but load the ENTIRE file into memory at once — for a multi-gigabyte log file, this would exceed the available heap memory. BufferedReader.readLine() or Files.lines() (which returns a Stream<String> that’s evaluated lazily/step by step), by contrast, each process only a small part at a time and are therefore suitable for arbitrarily large files. Files.lines() MUST sit within a try-with-resources block, because the underlying file handle otherwise stays open, even if the stream isn’t fully consumed.
See also: Files, BufferedReader, I/O Streams