← Skill tree CS Skill Tree 0 CSCD210

Reading a File with Scanner

Textbook: BJP (Reges and Stepp)

Where you are: Week 0 review > Reading a file with Scanner

Try This First

A program runs new File("scores.txt") for a file that does not exist, and no error appears. Decide why before reading on.

Reveal

new File(...) only stores the path; it does not touch the disk. The error appears one line later, when new Scanner(file) tries to open the file and throws FileNotFoundException.

Before You Start

Check each box you can do from memory. A box you cannot check yet is not a problem; it points you to a quick refresher, not a grade.

See Loops: for, while, and do-while for a quick review if any of the above felt uncertain.

Not sure? Take the 60-second self-check.

Try each from memory, then read the answer under it.

  1. What does a while loop need in order to stop? Its condition must become false at some point.
  2. What goes wrong if the condition never becomes false? The loop runs forever, an infinite loop.

If either felt shaky, a short review of the loop shapes will set it up.

What You Need To Walk In With

Walk into the next class able to state these:

You should be able to: open a file with the two-step idiom and write a read loop that ends cleanly at the end of the file.

How It Works

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public static int countLines(String filename) throws FileNotFoundException {
    File f = new File(filename);    // a path object; the disk is not touched yet
    Scanner sc = new Scanner(f);    // opens the file; can throw FileNotFoundException
    int n = 0;
    while (sc.hasNextLine()) {
        sc.nextLine();
        n = n + 1;
    }
    sc.close();                     // release the operating-system file handle
    return n;
}

Two parts are new compared to reading from the keyboard:

The cursor model

A l i c e \n B o b \n
^ cursor starts here

nextLine() reads from the cursor to the next newline, returns the text without the newline, and moves the cursor past it. hasNextLine() peeks ahead without moving the cursor and returns false at the end of the file, so the loop exits cleanly.

A file Scanner holds an operating-system file handle. Handles are limited and are not reclaimed reliably while the program runs, so call close() as soon as the reading is done.

Worked Example: Predict, Then Check

A file holds three lines: Alice, Bob, Carol. The loop above counts lines. Predict the returned value.

Reveal

3. Each pass hasNextLine() peeks true, nextLine() reads one line and advances the cursor, and n increases. After the third line the cursor is at the end, hasNextLine() returns false, and the loop exits with n equal to 3.

A Common Mistake

A frequent belief is that new File(name) opens the file, so a missing file should fail on that line. It does not: File is only a path. The open happens at new Scanner(file), which is where a missing file throws FileNotFoundException. Handle the exception on the method that builds the Scanner. (Source: BJP (Reges and Stepp), Ch 6.)

Go Deeper (optional)

For the curious: the explicit close() here is the foundation for try-with-resources, a later form that closes the Scanner automatically even if an error interrupts the reading. Learning the manual close() first makes clear what that automatic form is doing for you.

Check Yourself

Close the notes and answer each one from memory, then reveal it. Pulling an idea back from memory is one of the strongest ways to make it stick.

Check your understanding

Does new File(“scores.txt”) open the file or touch the disk?

Tier 1 · BJP (Reges and Stepp), Ch 6

Which call can throw FileNotFoundException?

Tier 1 · BJP (Reges and Stepp), Ch 6

Why call sc.close() after reading a file?

Tier 2 · BJP (Reges and Stepp), Ch 6

What does hasNextLine() do to the cursor?

Tier 2 · BJP (Reges and Stepp), Ch 6