The Stacks
UNIT 4: DATA COLLECTIONS · TOPIC 4.6

4.6 Using Text Files

New in the revised course. Reading a text file uses the same Scanner methods as keyboard input, plus a File object and one exception you must declare.

What you need to know

  • Open a file for reading: Scanner in = new Scanner(new File("data.txt"));. Both File (java.io) and Scanner (java.util) need imports.
  • Creating a Scanner on a File can throw FileNotFoundException (a checked exception). The method must declare throws FileNotFoundException in its header.
  • Read line by line: while (in.hasNextLine()) { String line = in.nextLine(); ... }. Read tokens: while (in.hasNext()) with next(), or hasNextInt() with nextInt().
  • Close the file when done: in.close();
  • Lines of text often need parsing: Integer.parseInt(str) and Double.parseDouble(str) convert String tokens to numbers.
  • The same nextInt/nextLine buffer trap from 1.4 applies to files.
  • A common pattern: read each line into an ArrayList so the data can be processed after the file is closed.

Worked example

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

public static ArrayList<Integer> readScores(String filename)
        throws FileNotFoundException
{
    Scanner in = new Scanner(new File(filename));
    ArrayList<Integer> scores = new ArrayList<Integer>();
    while (in.hasNextInt())
    {
        scores.add(in.nextInt());
    }
    in.close();
    return scores;
}
Exam tip: Three things the exam checks: the throws FileNotFoundException clause, the hasNext…/next… pair matching (hasNextLine with nextLine, hasNextInt with nextInt), and closing the Scanner. If a method opens a file and has no throws clause, it won't compile.

Going deeper

The nuance, edge cases, and connections that turn a 3 into a 5.

  • The pattern: Scanner in = new Scanner(new File("name.txt"));. File represents the path; Scanner reads from it using the exact same methods as keyboard input. Both need imports: java.io.File and java.util.Scanner.
  • FileNotFoundException is a checked exception — the compiler requires you to acknowledge it. Since you won't write try/catch on the exam, the acknowledgment is throws FileNotFoundException in the method header (import java.io.FileNotFoundException). Forget it → compile error.
  • Reading loops: pair the check with the read. hasNextLine() ↔ nextLine(); hasNext() ↔ next(); hasNextInt() ↔ nextInt(). Mismatching (hasNext with nextLine) can miss data or throw on trailing whitespace.
  • Parsing: file data is text. Integer.parseInt(token) and Double.parseDouble(token) convert. If a line has several values separated by spaces, next() reads them one at a time.
  • The nextInt/nextLine trap applies to files exactly as to keyboard input (1.4).
  • Close the Scanner when done: in.close(). Releases the file. The exam expects it.
  • Typical structure: open → loop reading into an ArrayList → close → process the list. Separating reading from processing keeps the file open briefly and makes the processing code testable.
  • This topic is new in the 2025–26 CED. Expect it to be tested — it's a signal the College Board wanted students to handle real data.

Mistakes that cost points

  • No throws clause. Compile error. Every method that opens a file needs it (or the method that calls it does).
  • Mismatched has/next. while (hasNext()) with nextLine() can behave unexpectedly on blank lines.
  • Reading a number with nextLine and not parsing. You get a String. Parse it.
  • Forgetting the imports. Three of them: File, FileNotFoundException, Scanner.

Practice questions

Written in the style of the real exam. Try each one before revealing the answer.

Q1 A method creates new Scanner(new File("in.txt")). Which of the following must be true for the code to compile?
  1. A The file must exist at compile time.
  2. B The method must declare throws FileNotFoundException.
  3. C The Scanner must be static.
  4. D The file must contain only integers.
Show answer

Answer: B. FileNotFoundException is a checked exception; the method header must declare it.

Q2 Which loop correctly reads every line of a text file using a Scanner sc?
  1. A while (sc.hasNext()) { String s = sc.nextLine(); }
  2. B while (sc.hasNextLine()) { String s = sc.nextLine(); }
  3. C while (sc.nextLine() != null) { }
  4. D for (int i = 0; i < sc.length(); i++) { String s = sc.nextLine(); }
Show answer

Answer: B. hasNextLine pairs with nextLine. Option A can throw on a trailing blank line; C throws at end of file; D doesn't compile.

Key vocabulary

File
a class representing a file on disk, passed to a Scanner to read it
FileNotFoundException
a checked exception thrown when a file can't be opened; must be declared
hasNextLine()
returns true if another line remains to be read