The Analogy: The Archive Reading-Room Clerk
In a records archive you do not wander into the stacks yourself. You hand a request slip to the reading-room clerk, who fetches the bound ledger, sets it on the desk, and reads it to you from the top down -- one entry at a time, in the order they were bound. You cannot skip to entry 400 without the clerk turning past the first 399; the ledger is read sequentially, front to back. When the clerk reaches the last entry, they tell you plainly "that is the end," and you know to stop asking. Reading a file in Java works exactly this way: you open a reader over the file, pull content from it in order, and watch for the end-of-stream signal that says there is nothing more to read.
There are two clerks on duty, and they suit different jobs. One is a meticulous parsing clerk who will read you the ledger field by field -- "the next word is FURNACE, the next number is 900" -- converting each token to the type you asked for as they go. That is Scanner: convenient when you want typed tokens, words, or numbers pulled out of the text for you. The other clerk just hands you whole pages at speed, a line at a time, and leaves the interpreting to you. That is BufferedReader: it reads large blocks of the file into a buffer in one trip and serves lines from memory, which is far faster for large files. Both read the same ledger; they differ in how much interpreting they do and how fast they go. See [[buffer-reader]] for the buffering clerk in full.
The end-of-file signal is the part beginners trip over, because the two clerks announce the end differently. Scanner answers a question -- hasNextLine() returns false, hasNextInt() returns false -- so you ask before you read. BufferedReader.readLine() instead hands back null when the file is exhausted, so you read and then check. Getting these right is the difference between a clean read and either an exception at the end or a loop that never stops. The clerk always tells you when the ledger is finished; you just have to listen for the form the answer takes.
The failure mode is forgetting to return the ledger to the stacks. If you walk out of the reading room with the ledger still on your desk, nobody else can request it -- the record is locked out until someone notices. A file reader holds an operating-system handle open the same way; leave it unclosed and the file stays locked, the handle leaks, and a long-running program eventually exhausts the handles it is allowed. This is precisely why file reading is the textbook case for the [[try-with-resources]] airlock: declare the reader in the try clause and it is always returned to the stacks, even when the reading throws partway through.
Syntax or Core Structure
Scanner reads from any source. In production you pass new Scanner(new File("data.txt")); here the source is an in-memory string so the output is reproducible, but the reading loop is identical.
import java.util.Scanner;
public class ReadLines {
public static void main(String[] args) {
String ledger = "furnace 900
cooling 40
press 12";
int line = 0;
try (Scanner reader = new Scanner(ledger)) {
while (reader.hasNextLine()) {
line++;
System.out.println("line " + line + ": " + reader.nextLine());
}
}
System.out.println("total: " + line);
}
}
Output:
line 1: furnace 900
line 2: cooling 40
line 3: press 12
total: 3
The Scanner is declared in the try (...) clause, so it closes automatically when the loop ends. hasNextLine() is asked before each nextLine(), so the loop stops cleanly at end-of-input rather than throwing. Swapping the string for new File("data.txt") changes nothing about the loop -- only the source.
Technical Depth: The Two Readers, End-Of-File Signals, And Typed Parsing
Scanner Versus BufferedReader
Both read text sequentially, but they trade convenience against speed and differ in how they report the end.
| Aspect | Scanner | BufferedReader |
|---|---|---|
| Reads | Tokens, lines, or typed values | Whole lines as String |
| End-of-input | hasNextLine() returns false | readLine() returns null |
| Speed on large files | Slower (parsing overhead) | Faster (block buffering) |
IOException on read | Swallowed; check ioException() | Thrown directly |
Reach for Scanner when you want it to parse numbers and words for you and the file is small. Reach for BufferedReader when you are streaming large text and will interpret lines yourself, or when you want IO errors surfaced as exceptions rather than hidden. The IOException row is the one that surprises people and the next subsection returns to it.
BufferedReader And The null End Signal
BufferedReader reads whole lines and signals end-of-input by returning null from readLine(). The idiomatic loop assigns and tests in one condition. Here the source is a StringReader so the run is reproducible; a file version wraps a FileReader instead.
import java.io.BufferedReader;
import java.io.StringReader;
import java.io.IOException;
public class ReadFast {
public static void main(String[] args) throws IOException {
String ledger = "furnace 900
cooling 40
press 12";
int count = 0;
try (BufferedReader reader =
new BufferedReader(new StringReader(ledger))) {
String row;
while ((row = reader.readLine()) != null) {
count++;
System.out.println("row " + count + ": " + row);
}
}
System.out.println("rows: " + count);
}
}
Output:
row 1: furnace 900
row 2: cooling 40
row 3: press 12
rows: 3
The (row = reader.readLine()) != null idiom reads a line and tests it at once; the loop ends the moment readLine() returns null. Because readLine() declares IOException, main declares throws IOException -- the error is surfaced, not swallowed, which is the behaviour the comparison table contrasted with Scanner.
Typed Parsing Is Where Scanner Earns Its Keep
The reason to accept Scanner's slower speed is that it parses typed tokens for you. hasNextInt() and nextInt() read integers directly, skipping the manual Integer.parseInt a BufferedReader line would need. Each typed read has a matching guard that reports whether the next token fits.
| Read method | Guard | Returns |
|---|---|---|
nextInt() | hasNextInt() | The next token as an int |
nextDouble() | hasNextDouble() | The next token as a double |
next() | hasNext() | The next whitespace-delimited word |
nextLine() | hasNextLine() | The rest of the current line |
Always call the guard before the read: an unguarded nextInt() on a non-integer token throws InputMismatchException, and one past the end throws NoSuchElementException.
import java.util.Scanner;
public class SumReadings {
public static void main(String[] args) {
String readings = "12 7 3 20 8";
int sum = 0;
int n = 0;
try (Scanner sc = new Scanner(readings)) {
while (sc.hasNextInt()) {
sum += sc.nextInt();
n++;
}
}
System.out.println("count: " + n);
System.out.println("sum: " + sum);
}
}
Output:
count: 5
sum: 50
Scanner reads each integer as an int with no explicit conversion, guarding each read with hasNextInt(). The five readings sum to 50. Doing this with BufferedReader would mean splitting the line and calling Integer.parseInt on each field yourself -- more code, but faster and with IO errors thrown rather than hidden.
Real World Example: Scanning A Log For Matches
A common real task is reading a log line by line, counting the lines, and finding matches. This uses BufferedReader because logs are large and we interpret lines ourselves. The source is an in-memory multi-line string so the result is deterministic; in production it is new BufferedReader(new FileReader("app.log")).
import java.io.BufferedReader;
import java.io.StringReader;
import java.io.IOException;
public class LogScan {
// Returns {total lines, matching lines, first matching line number}.
static int[] scan(String text, String needle) throws IOException {
int total = 0, hits = 0, first = 0;
try (BufferedReader reader =
new BufferedReader(new StringReader(text))) {
String line;
while ((line = reader.readLine()) != null) {
total++;
if (line.contains(needle)) {
hits++;
if (first == 0) first = total;
}
}
}
return new int[] { total, hits, first };
}
public static void main(String[] args) throws IOException {
String log = "INFO start
"
+ "WARN disk low
"
+ "INFO request ok
"
+ "WARN retry
"
+ "INFO stop";
int[] r = scan(log, "WARN");
System.out.println("lines: " + r[0]);
System.out.println("hits: " + r[1]);
System.out.println("first: " + r[2]);
}
}
Output:
lines: 5
hits: 2
first: 2
The scan method reads the log a line at a time and never holds more than one line in memory, which is the whole reason to stream rather than slurp. It counts every line, tallies the ones containing the needle, and records the first match's line number -- returning all three as a small array. Because readLine() can fail on a real file, scan declares throws IOException and lets the caller decide what to do, exactly as [[throws-declaration]] prescribes; nothing is swallowed.
The try-with-resources around the reader guarantees the handle is released whether the scan finishes or throws partway through. That matters more here than it looks: a log-scanning routine might run thousands of times in a long-lived service, and a single leaked handle per run exhausts the process's file-descriptor limit within hours. The airlock makes the leak structurally impossible.
The choice of BufferedReader over Scanner here is deliberate and worth defending. Logs are large, we only want raw lines, and we want an IO failure to surface as an exception rather than be silently absorbed. Scanner would have parsed nothing useful for us and hidden any read error behind an innocent-looking end-of-input. For this shape of task the faster, more honest reader is the right tool.
The design is not without genuine limits, and one is a real Java wart. Scanner swallows IOException: if the underlying source fails mid-read, Scanner reports end-of-input rather than throwing, and you only discover the failure by calling ioException() afterwards -- a check almost nobody writes, so partial reads pass as complete. Beyond that, both readers default to the platform's charset unless you pass one explicitly, so a file written as UTF-8 can decode as garbage on a machine with a different default. And reading line by line assumes the data is line-structured; a file that is one enormous line defeats readLine() and can still blow the heap. The honest rule is to specify the charset, prefer BufferedReader for large text, and never assume a read that returned without complaint actually read everything.
Common Mistakes
- Not closing the reader. Opening a
ScannerorBufferedReaderand never closing it leaks the OS file handle and leaves the file locked. Declare it in a [[try-with-resources]] clause so it always closes.
- Calling
nextLine()withouthasNextLine(). Reading past the end of aScannerthrowsNoSuchElementException. Guard every read with the matchinghasNext...check, or loop on that check.
- Forgetting the
nullcheck onreadLine(). ABufferedReaderloop that does not testreadLine()againstnulleither never terminates or dereferencesnull. Use the(line = reader.readLine()) != nullidiom.
- Trusting
Scannerto surface IO errors.ScannerswallowsIOExceptionand reports it as end-of-input, so a failed read looks like a finished one. When errors must be seen, useBufferedReader, whosereadLine()throws.
- Relying on the default charset. Reading without specifying a charset decodes with the platform default, so the same file reads differently on different machines. Pass an explicit charset such as
StandardCharsets.UTF_8.
- Slurping a huge file into memory. Reading an entire multi-gigabyte file into a
Stringor list exhausts the heap. Stream it line by line and keep only what you need, as the log scanner does.
- Mixing
nextInt()andnextLine()carelessly.nextInt()leaves the line's trailing newline in the buffer, so the nextnextLine()returns an empty string. Consume the newline deliberately or read consistently by line.
- Assuming relative paths resolve to the source file. A relative path like
"data.txt"resolves against the process working directory, not the location of the.javafile. Run from the expected directory or use an absolute path.
- Catching
IOExceptionwhen you meanFileNotFoundException. A broadcatch (IOException e)treats a missing file and a mid-read failure identically. CatchFileNotFoundExceptionfirst when the two need different handling.
Best Practices
- Always read inside try-with-resources. Declare the reader in the
try (...)clause so its handle is released on every exit path, closing the file even when the read throws.
- Match the end-of-input check to the reader. Use
hasNextLine()/hasNextInt()before aScannerread, and testreadLine()againstnullfor aBufferedReader.
- Prefer
BufferedReaderfor large text. Its block buffering makes it markedly faster on big files, and itsreadLine()surfaces IO errors as exceptions instead of hiding them.
- Specify the charset explicitly. Pass
StandardCharsets.UTF_8(or the file's actual encoding) rather than relying on the platform default, so reads are portable across machines.
- Stream, do not slurp. Process a file line by line and keep only what you need, so memory use stays bounded no matter how large the input grows.
- Choose the reader by the job. Use
Scannerwhen you want typed tokens parsed for you from small input; useBufferedReaderwhen you want fast raw lines and honest IO errors.
- Let
IOExceptionpropagate. Declarethrows IOExceptionand let the caller decide, rather than swallowing a read failure or converting it into a silent empty result.
- Distinguish "missing" from "failed". Catch
FileNotFoundExceptionseparately from a generalIOExceptionwhen a missing file and a read failure call for different responses.
Practice Exercises
- The line counter. Using a
BufferedReaderover a multi-lineStringsource (viaStringReader), count and print exactly how many lines it contains. Confirm the loop ends whenreadLine()returnsnull, and that the reader is declared in a try-with-resources clause.
- Search and report. Read a multi-line
Stringline by line and, for a given search word, print the number of the first line that contains it (or a "not found" message). Track the line number as you read, and report the first match only.
- The average. A
Stringsource contains one integer per line. UsingScannerwithhasNextInt()/nextInt(), read them all and print the count, the sum, and the integer average. Ensure the loop stops cleanly at end-of-input and the division uses the count actually read.