Lesson 4.6: Using Text Files
Lesson 4.6: Using Text Files
What You'll Learn
-
4.6.A: Read data from a file using the
FileandScannerclasses. - Write the correct import statements for file reading.
- Construct a
Scannerconnected to aFileobject. - Use
hasNext(),nextLine(), andnextInt()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, andjava.util.Scanner. - Create a
Fileobject, pass it tonew 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 orthrows. - Always call
scanner.close()when done.
Practice Questions
import java.util.File; and import java.io.Scanner;
import java.io.File; and import java.util.Scanner;
import java.io.*; onlyFile 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.FileNotFoundException that must be handled.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.sc.nextLine() != null
sc.hasNextLine() == true
sc.length() > 0
sc.hasNext()
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.nextInt() do when called on a Scanner reading a file?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()."input.txt"?Scanner sc = new Scanner("input.txt");
Scanner sc = new Scanner(System.in);
File f = new File("input.txt");
Scanner sc = new Scanner(f);
Scanner sc = new File("input.txt");
Mastery: Reading Data from Files
numbers.txt contains the values 3, 7, 2, 9 — one per line. Which code correctly reads them into an ArrayList named vals?Scanner sc = new Scanner("numbers.txt");
while (sc.hasNext()) {
vals.add(sc.nextInt());
}
File f = new File("numbers.txt");
Scanner sc = new Scanner(f);
while (sc.hasNext()) {
vals.add(sc.nextInt());
}
sc.close();
File f = new File("numbers.txt");
Scanner sc = new Scanner(f);
for (int i = 0; i < 4; i++) {
vals.add(sc.nextInt());
}
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
vals.add(sc.nextInt());
}
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.while (sc.hasNext()) {
String name = sc.nextLine();
int score = Integer.parseInt(sc.nextLine());
}
while (sc.hasNext()) {
int score = sc.nextInt();
String name = sc.nextLine();
}
while (sc.hasNext()) {
String name = sc.nextLine();
String score = sc.nextLine();
int s = score.length();
}
while (sc.hasNext()) {
int score = Integer.parseInt(sc.nextLine());
String name = sc.nextLine();
}
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.
Message Sent!
Thanks for reaching out. I'll get back to you within 24 hours.
Prefer email? Reach me directly at [email protected]