Lesson 4.6: Using Text Files

AP CSA Hub Unit 4 4.1 Lesson Ex 1 Ex 2 Quiz 4.2 Lesson Ex 1 Ex 2 Quiz 4.3 Lesson Ex 1 Ex 2 Quiz 4.4 Lesson Ex 1 Ex 2 Quiz 4.5 Lesson Ex 1 Ex 2 Quiz 4.6 Lesson Ex 1 Ex 2 Quiz 4.7 Lesson Ex 1 Ex 2 Quiz 4.8 Lesson Ex 1 Ex 2 Quiz 4.9 Lesson Ex 1 Ex 2 Quiz 4.10 Lesson Ex 1 Ex 2 Quiz 4.11 Lesson Ex 1 Ex 2 Quiz 4.12 Lesson Ex 1 Ex 2 Quiz 4.13 Lesson Ex 1 Ex 2 Quiz 4.14 Lesson Ex 1 Ex 2 Quiz 4.15 Lesson Ex 1 Ex 2 Quiz 4.16 Lesson Ex 1 Ex 2 Quiz 4.17 Lesson Ex 1 Ex 2 Quiz

Unit 4 · Lesson 4.6 · Using Text Files

Lesson 4.6: Using Text Files

🕒 35-45 min · 10 Practice Questions · Scanner · File I/O · hasNextInt

What You'll Learn

  • Read text data from a file using the File and Scanner classes.
  • Handle FileNotFoundException, a checked exception the compiler requires you to catch or declare.
  • Use hasNextLine, hasNext and hasNextInt to read a file without knowing its length in advance.
  • Recognize why file-reading code has to plan for a file that might not exist or might be empty.

Key Vocabulary

Term Definition
File An object representing a path to a file on disk. Creating one does not guarantee the file actually exists.
FileNotFoundException A checked exception a Scanner throws when it cannot locate the file it was given.
checked exception An exception the compiler forces you to either catch or declare with throws. Code that does neither will not compile.
hasNextLine() A Scanner method that reports whether another line of input remains, without consuming it.
delimiter The character or characters Scanner uses to separate tokens. Whitespace by default.

Opening a File

A Scanner can read from a file the same way it reads from the keyboard, once it is built on a File object instead of System.in.

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

Scanner input = new Scanner(new File("scores.txt"));

⚠️ This Line Alone Will Not Compile

new Scanner(new File(...)) can throw FileNotFoundException, and that exception is checked. A method that contains this line must either catch it or declare throws FileNotFoundException on its own signature, or the compiler refuses the whole file.

public static void main(String[] args) throws FileNotFoundException {
    Scanner input = new Scanner(new File("scores.txt"));
    // ...
}

Reading a File Without Knowing Its Length

The same hasNextInt pattern used for unknown-length input on standard input works identically over a file, because both are just Scanner sources.

int total = 0;
while (input.hasNextInt()) {
    int value = input.nextInt();
    total = total + value;
}

⚠️ Check Before You Consume

Calling nextInt() when nothing is left throws NoSuchElementException. hasNextInt() checks without consuming, which is exactly what guards against that.

The Same Scanner, a Different Source

📌 Nothing About the Reading Logic Changes

Scanner(System.in) and Scanner(new File(...)) are driven by the exact same hasNext/next methods. A loop written to read unknown-length data from the keyboard reads a file the same way, because the source is the only thing that changed.

Practice Questions

MCQ 1
Which statement about opening a file with Scanner is true?
A new Scanner(new File("x.txt")) can throw FileNotFoundException, a checked exception that must be caught or declared
B new Scanner(new File("x.txt")) never fails, since File objects always exist
C FileNotFoundException is an unchecked exception, so handling it is optional
D Scanner cannot be built from a File object, only from System.in
A. A File object can be created for a path that does not exist; the failure surfaces when Scanner tries to open it. That failure is FileNotFoundException, a checked exception, so it must be caught or declared.
MCQ 2
What does hasNextLine() do?
A Reads and returns the next line, consuming it
B Deletes the current line from the file
C Reports whether another line exists, without consuming any input
D Reports whether the file itself exists
C. hasNextLine() only checks; it never consumes a token or a line. nextLine() is the method that actually reads and returns one.
MCQ 3
Why does this code fail to compile?
public static void main(String[] args) {
    Scanner input = new Scanner(new File("data.txt"));
}
A Scanner cannot be constructed from a File
B main methods are not allowed to open files
C File objects require their own try block by Java's syntax rules
D FileNotFoundException is a checked exception that main must either catch or declare with throws, and this code does neither
D. The constructor call can throw a checked exception. Since main here neither catches it nor declares throws FileNotFoundException, the compiler refuses the file.
MCQ 4
What happens if nextInt() is called after hasNextInt() has already returned false?
A It returns 0
B It throws NoSuchElementException
C It waits for more input to arrive
D It safely returns the last value read again
B. Once hasNextInt() reports false, there is no more int-shaped data. Calling nextInt() anyway throws NoSuchElementException, exactly what the hasNextInt guard exists to prevent.
MCQ 5
A grader pipes a file's contents in on standard input instead of handing you a real file, since Judge0 has no filesystem. Which statement about the Scanner code you write is true?
A The code must be completely different from code that reads an actual file
B Scanner cannot read from standard input at all
C Scanner(System.in) and Scanner(new File(...)) are driven by the exact same hasNext and next methods, so the same read loop works either way
D Reading from standard input never throws the exceptions file reading can throw
C. The substitution works precisely because both are Scanner sources read through identical methods.
Tier 3 · AP Mastery

Mastery: Using Text Files

MCQ 6
What does this print when data.txt is completely empty (holds nothing at all)?
Scanner input = new Scanner(new File("data.txt"));
int count = 0;
while (input.hasNextInt()) {
    input.nextInt();
    count++;
}
System.out.println(count);
A 0
B A compile error
C NoSuchElementException is thrown
D Nothing prints; the program hangs waiting for input
A. hasNextInt() is false immediately on an empty file, so the loop body never runs and count stays at its initial value, 0.
MCQ 7
What kind of exception is FileNotFoundException, and what does that mean for code that opens a file?
A Unchecked; handling it is optional
B It does not exist as a real class in java.io
C An Error rather than an Exception, so it can never be caught
D Checked; the compiler forces you to catch it or declare it with throws
D. FileNotFoundException extends IOException, a checked exception, which is exactly why file-opening code needs a catch block or a throws declaration.
MCQ 8
Which of these correctly lets FileNotFoundException propagate out of main rather than catching it?
A public static void main(String[] args) { ... }
B public static void main(String[] args) throws FileNotFoundException { ... }
C public static void main(String[] args) catches FileNotFoundException { ... }
D public static void main(String[] args) throws Exception.printStackTrace() { ... }
B. throws is the keyword that declares a method may propagate a checked exception instead of handling it. catches is not a Java keyword, and D is not valid syntax at all.
MCQ 9
A student guards a loop reading integers with hasNext() instead of hasNextInt(). Why is this riskier on a file that is supposed to hold only integers?
A hasNext() only confirms that a token exists at all, not that it will parse as an int, so a malformed token can still make nextInt() throw InputMismatchException
B hasNext() is always slower than hasNextInt()
C hasNext() cannot be combined with nextInt() at all
D There is no real difference between the two
A. hasNext() checks for the presence of any token, not its shape. A stray non-numeric token passes the hasNext() check and then breaks nextInt().
MCQ 10
A program must total every value in a file without ever being told how many values it holds. Which loop is correct?
A for (int i = 0; i < 100; i++) { total += input.nextInt(); }
B while (true) { total += input.nextInt(); }
C while (input.hasNextInt()) { total += input.nextInt(); }
D int n = input.nextInt(); while (n != -1) { total += n; n = input.nextInt(); }
C. Hardcoding a count assumes a length that may be wrong; looping forever eventually throws once data runs out; assuming a -1 sentinel assumes a value that could legitimately appear in real data. Only the hasNextInt guard is correct for genuinely unknown length.

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]