Lesson 4.6: Using Text Files

Unit 4 · Lesson 4.6 · File I/O

Lesson 4.6: Using Text Files

🕑 35–45 min · 8 Practice Questions · New for 2025-26 · File · Scanner

What You'll Learn

  • 4.6.A: Read data from a file using the File and Scanner classes.
  • Write the correct import statements for file reading.
  • Construct a Scanner connected to a File object.
  • Use hasNext(), nextLine(), and nextInt() to read file content.
  • Explain why file reading must be wrapped in a try-catch or declared to throw an exception.

📌 New for 2025-26

File I/O is a brand-new addition to the AP CSA curriculum this year. Text file reading with File and Scanner was not tested before 2026. It directly connects to data sets (Lesson 4.15) — reading a file is how real programs load data at the start of execution.

Key Vocabulary

Term Definition
File A class in java.io that represents a file on disk. Used to connect a Scanner to a file by passing the File object to the Scanner constructor.
Scanner A class in java.util that reads input — from the keyboard (System.in) or from a file. Provides methods to read different data types.
hasNext() Returns true if the Scanner has more tokens to read; false if the end of the file has been reached.
FileNotFoundException A checked exception thrown when the specified file does not exist. Must be handled with try-catch or declared with throws.

Required Imports

File reading requires two imports:

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

Basic File Reading Pattern

The standard pattern: create a File object, pass it to a Scanner, read with a while loop, close when done.

try {
    File myFile = new File("data.txt");
    Scanner fileScanner = new Scanner(myFile);

    while (fileScanner.hasNext()) {
        String line = fileScanner.nextLine();
        System.out.println(line);
    }

    fileScanner.close();
} catch (FileNotFoundException e) {
    System.out.println("File not found.");
}

📌 Why try-catch Is Required

Creating a Scanner from a File can throw a FileNotFoundException — a checked exception that Java requires you to handle. If you don't wrap it in try-catch (or declare throws FileNotFoundException on the method signature), the code won't compile.

Scanner Methods for File Reading

Method Returns Description
hasNext() boolean True if there is another token to read
nextLine() String Returns and consumes the next full line of text
nextInt() int Returns and consumes the next integer token
next() String Returns and consumes the next whitespace-delimited token

✅ Example: Reading Integers from a File

Suppose scores.txt contains one integer per line: 92, 85, 78, 90.

try {
    File f = new File("scores.txt");
    Scanner sc = new Scanner(f);
    ArrayList scores = new ArrayList();

    while (sc.hasNext()) {
        scores.add(sc.nextInt());
    }
    sc.close();
} catch (FileNotFoundException e) {
    System.out.println("scores.txt not found.");
}
// scores: [92, 85, 78, 90]

This is the complete read-into-collection pattern: open file, loop with hasNext(), add each value, close. This connects directly to Lesson 4.15 where a file loads a data set.

Summary

  • Import java.io.File, java.io.FileNotFoundException, and java.util.Scanner.
  • Create a File object, pass it to new Scanner(file).
  • Use hasNext() as the while-loop condition to avoid reading past the end of the file.
  • Use nextLine() for full lines, nextInt() for integers, next() for tokens.
  • File reading throws FileNotFoundException — must use try-catch or throws.
  • Always call scanner.close() when done.

Practice Questions

MCQ 1
Which pair of imports is required to read from a text file in Java?
A import java.util.File; and import java.io.Scanner;
B No imports needed — File and Scanner are built in.
C import java.io.File; and import java.util.Scanner;
D import java.io.*; only
C. File is in java.io. Scanner is in java.util. A swaps the packages. B is wrong — neither class is auto-imported. D would import File but not Scanner.
MCQ 2
Why must file-reading code be wrapped in a try-catch block?
A Creating a Scanner from a File throws a checked FileNotFoundException that must be handled.
B The Scanner class is abstract and requires exception handling.
C File reading is always slow and try-catch improves performance.
D try-catch is optional — the code will compile without it.
A. FileNotFoundException is a checked exception — Java requires it to be either caught (try-catch) or declared (throws). D is wrong: without handling it, the code won't compile.
MCQ 3
Which method should be used as the while-loop condition when reading all lines from a file?
A sc.nextLine() != null
B sc.hasNextLine() == true
C sc.length() > 0
D sc.hasNext()
D. hasNext() returns true while there are more tokens to read. A would throw an exception when there's nothing left — you can't call nextLine() on an exhausted scanner. B works but the == true is redundant. C is wrong — Scanner has no length() method.
MCQ 4
What does nextInt() do when called on a Scanner reading a file?
A Returns the total number of integers in the file.
B Returns and consumes the next integer token from the file.
C Returns the next full line as an integer.
D Returns false if the next token is not an integer.
B. nextInt() reads and returns the next whitespace-delimited token, interpreted as an integer. It advances the scanner's position — "consumes" means the token won't be read again. D describes hasNextInt(), not nextInt().
MCQ 5
Which correctly constructs a Scanner to read from a file named "input.txt"?
A
Scanner sc = new Scanner("input.txt");
B
Scanner sc = new Scanner(System.in);
C
File f = new File("input.txt");
Scanner sc = new Scanner(f);
D
Scanner sc = new File("input.txt");
C. A passes a String to Scanner — this scans the string itself, not the file. B connects to keyboard input. D tries to assign a File to a Scanner variable — type mismatch. C correctly creates a File object first, then passes it to Scanner.
Tier 3 · AP Mastery

Mastery: Reading Data from Files

MCQ 6
A file numbers.txt contains the values 3, 7, 2, 9 — one per line. Which code correctly reads them into an ArrayList named vals?
Predict before reading the options.
A
Scanner sc = new Scanner("numbers.txt");
while (sc.hasNext()) {
    vals.add(sc.nextInt());
}
B
File f = new File("numbers.txt");
Scanner sc = new Scanner(f);
while (sc.hasNext()) {
    vals.add(sc.nextInt());
}
sc.close();
C
File f = new File("numbers.txt");
Scanner sc = new Scanner(f);
for (int i = 0; i < 4; i++) {
    vals.add(sc.nextInt());
}
D
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
    vals.add(sc.nextInt());
}
B. A passes a String literal to Scanner — reads the string "numbers.txt" as text, not the file. C hardcodes 4 iterations — fragile, won't work if the file changes. D reads from keyboard input. B correctly constructs from a File object, loops with hasNext(), and closes the scanner.
MCQ 7
A programmer forgets the try-catch when creating a Scanner from a File. What happens?
A The program runs normally if the file exists.
B A runtime exception is thrown when the file is not found.
C The Scanner reads an empty file by default.
D The code does not compile — FileNotFoundException is a checked exception.
D. FileNotFoundException is a checked exception. The Java compiler enforces that checked exceptions are either caught or declared. Without try-catch or throws FileNotFoundException, the code will not compile — regardless of whether the file exists at runtime.
MCQ 8
A file contains student names and scores on alternating lines: "Alice" on line 1, "92" on line 2, "Ben" on line 3, "85" on line 4. Which read order is correct?
Predict before reading the options.
A
while (sc.hasNext()) {
    String name = sc.nextLine();
    int score = Integer.parseInt(sc.nextLine());
}
B
while (sc.hasNext()) {
    int score = sc.nextInt();
    String name = sc.nextLine();
}
C
while (sc.hasNext()) {
    String name = sc.nextLine();
    String score = sc.nextLine();
    int s = score.length();
}
D
while (sc.hasNext()) {
    int score = Integer.parseInt(sc.nextLine());
    String name = sc.nextLine();
}
A. The file has name first, then score. Read in that order: nextLine() for the name string, nextLine() for the score string then parse it. B reads score before name — wrong order. C reads both as strings but uses score.length() instead of parsing the integer value. D reads score first — wrong order.

Get in Touch

Whether you're a student, parent, or teacher — I'd love to hear from you.

Just want free AP CS resources?

Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.

Typically responds within 24 hours

Message Sent!

Thanks for reaching out. I'll get back to you within 24 hours.

🏫 Welcome, fellow educator!

I offer curriculum resources, practice materials, and study guides designed for AP CS teachers. Let me know what you're looking for — whether it's classroom materials, a guest speaker, or Teachers Pay Teachers resources.

Email

[email protected]

📚

Courses

AP CSA, CSP, & Cybersecurity

Response Time

Within 24 hours

Prefer email? Reach me directly at [email protected]