File I/O
Scanner + File + a while loop — the entire AP exam file-reading toolkit in one page.
- A file is storage for data that persists when the program is not running, and can be retrieved during execution.
new File("scores.txt")does not open, read, or create the file — it only builds an object holding the pathname.- The only
Filemember on the reference is the constructorFile(String str), wherestris the pathname. - If the file named cannot be opened, the program terminates — there is no null return and no empty Scanner to check.
- A method that builds a
Scannerfrom aFilemust declarethrows IOExceptionor it will not compile. - Reading a file needs three imports:
FileandIOExceptionfromjava.io, andScannerfromjava.util. - Use
.hasNext()as the loop condition for almost every file-reading problem; it works no matter what type comes next. - There is one cursor; every read method moves it forward, while
.hasNext()only peeks and never moves it. - Read the whole line, then
line.split(",")into aString[]; convert numbers withInteger.parseIntorDouble.parseDouble. - Seed a maximum with the first value, not 0: an all-negative file seeded at 0 reports a value not in the file.
1The File Class
File reading is new to the AP CS A course framework, and it is the one place where your program reaches outside itself for data. Everything starts with the File class.
Before any of the syntax, the reason the topic exists at all: a file is storage for data that persists when the program is not running, and that data can be retrieved during execution. Every variable, object and collection your program builds disappears the moment it stops. A file does not — which is why it is the only way a program can be handed something a previous run produced.
1.1 A File Object Is a Path, Not an Open File
This is the single most misread line in the whole topic:
import java.io.File;
File dataFile = new File("scores.txt");
That statement does not open the file. It does not read it, create it, or check that it exists. All it builds is an object holding the pathname you gave it — a note that says "the file I mean is called scores.txt." The data on disk is untouched.
The only File member on the Java Quick Reference is the constructor File(String str), where str is the pathname. You will never be asked to call a method on a File object — its entire job is to be handed to a Scanner.
1.2 When the Path Is Wrong
Because constructing a File never checks whether the file exists, a bad filename causes no trouble at all on that line. The failure arrives later, on the line that actually tries to open it:
File f = new File("scoers.txt"); // typo — but this line is fine
Scanner reader = new Scanner(f); // this is where it fails
If the file named cannot be opened, the program stops. The CED states this plainly: if the file name is invalid, the program will terminate. There is no "returns null" and no empty Scanner to check for — execution ends.
1.3 Why throws IOException Is Required
Java forces you to acknowledge that opening a file might fail. You cannot simply ignore the possibility — code that opens a file will not compile unless it says what happens when the file cannot be opened.
The way the AP course does this is to add throws IOException to the header of the method that uses the file:
public static void readScores() throws IOException
{
Scanner reader = new Scanner(new File("scores.txt"));
// ... read the file ...
reader.close();
}
This is the mistake that costs points on free response. A method that builds a Scanner from a File and has no throws IOException in its header does not compile. It is not a runtime problem or a style preference — the code is rejected before it ever runs. If a question asks you to write a method that reads a file, put it in the header.
1.4 Two Imports, Two Packages
File reading pulls classes from two different places, and mixing them up is a common slip:
| Import | Package | What it brings |
|---|---|---|
import java.io.File; | java.io | The File class |
import java.io.IOException; | java.io | The IOException class |
import java.util.Scanner; | java.util | The Scanner class |
Scanner is the odd one outFile and IOException are input/output classes, so they live in java.io. Scanner is a general-purpose utility, so it lives in java.util — the same package as ArrayList. Reading a file needs all three.
2Reading Files with Scanner
A Scanner reads a file when you pass it a File object. That is the only Scanner constructor the AP exam uses:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public static void readFile() throws IOException
{
Scanner reader = new Scanner(new File("scores.txt"));
while (reader.hasNext())
{
String line = reader.nextLine();
System.out.println(line);
}
reader.close();
}
throws IOException is requiredAny method that creates a Scanner with a File must declare throws IOException in its method signature. This tells Java the file might not exist at runtime.
This is the only exception handling you need for AP File I/O — no try/catch blocks are required or tested.
3Scanner Methods
The Scanner methods most commonly tested on the AP exam:
| Method | What it does |
|---|---|
.nextInt() | Reads and returns the next int |
.nextDouble() | Reads and returns the next double |
.nextBoolean() | Reads and returns the next boolean |
.nextLine() | Reads and returns the rest of the current line as a String |
.next() | Reads and returns the next whitespace-delimited token as a String |
.hasNext() | Returns true if there is more data to read, false at end of file |
.close() | Closes the Scanner and releases the file |
.hasNext() is the go-to loop checkUse .hasNext() as your loop condition for almost every file-reading problem — it works no matter what type of data comes next. If you need to check for a specific type, type-specific checks like .hasNextInt() exist, but for most exam problems plain .hasNext() is all you need.
Scanner method reads forward from wherever the last one stopped. Nothing rewinds, and nothing re-reads.4The Standard File-Reading Loop
The pattern you will use for almost every file-reading problem:
Scanner reader = new Scanner(new File("data.txt"));
while (reader.hasNext())
{
// read data here using next(), nextLine(), nextInt(), etc.
}
reader.close();
.hasNext()peeks at the file. If there's more data, the loop body runs.- Inside the loop, you call
.nextLine(),.nextInt(),.next(), etc. to consume data. - After reading, the Scanner advances its position in the file.
- When all data has been consumed,
.hasNext()returnsfalseand the loop ends.
4.1 Running Trace — Where the Scanner Sits
A Scanner keeps a position in the file, and every read moves it forward. Take this three-line file:
Kim 88
Osei 91
Diaz 79
and this loop:
while (reader.hasNext())
{
String name = reader.next();
int score = reader.nextInt();
System.out.println(name + " scored " + score);
}
| Call | Returns | Position after the call |
|---|---|---|
.hasNext() | true | start of file |
.next() | "Kim" | just after Kim |
.nextInt() | 88 | just after 88 |
.hasNext() | true | unchanged — peeking never moves |
.next() | "Osei" | just after Osei |
| … two more rounds … | ||
.hasNext() | false | end of file — loop exits |
.hasNext() looks, the read methods moveChecking never consumes anything, so calling .hasNext() twice in a row gives the same answer twice. Only .next(), .nextInt(), .nextLine() and friends advance the position. A loop that checks but never reads runs forever.
The loop above reads two values each pass but checks .hasNext() only once. That is safe here because the file is known to hold complete name/score pairs. When a file might end mid-pair, check before each read instead.
5Reading Different Types of Data
5.1 Read Lines
If each line of the file is a complete record:
while (reader.hasNext())
{
String line = reader.nextLine();
System.out.println(line);
}
5.2 Read Integers
If the file contains integers separated by spaces or newlines:
int sum = 0;
while (reader.hasNext())
{
int n = reader.nextInt();
sum = sum + n;
}
System.out.println("Sum: " + sum);
5.3 Read Tokens (Words)
.next() reads one whitespace-delimited chunk at a time:
while (reader.hasNext())
{
String word = reader.next();
System.out.println(word);
}
If the file contains Hello world foo bar, this prints each word on its own line.
6Parsing Lines with .split()
Many data files use comma-separated values (CSV). Read the whole line, then .split() it.
Suppose roster.csv contains:
Son,7,Forward
Haaland,9,Forward
Salah,11,Forward
Scanner reader = new Scanner(new File("roster.csv"));
while (reader.hasNext())
{
String line = reader.nextLine();
String[] parts = line.split(",");
String name = parts[0]; // "Son"
int number = Integer.parseInt(parts[1]); // 7
String position = parts[2]; // "Forward"
System.out.println(name + " #" + number);
}
reader.close();
.split(), parseInt(), and parseDouble() are all on the reference sheetThese are the tools for turning raw file data into usable values:
line.split(",")→String[]array (one piece per delimiter)Integer.parseInt("7")→intvalue 7Double.parseDouble("3.14")→doublevalue 3.14
Split by commas, not spaces — space characters are visually ambiguous and hard to count on printed exams, so data files on the exam use comma delimiters.
String.7Mixing .nextLine() With Other Methods
.nextLine() and the token-based methods (.nextInt(), .nextDouble(), .next()) treat whitespace differently. .nextLine() consumes through the end of the current line, while the others stop as soon as their value ends — so calling .nextLine() right after one of them can return the empty string.
The College Board lists this whitespace difference as essential knowledge, then excludes it from assessment: writing or analyzing code that uses both .nextLine() and other Scanner methods on the same input source is outside the scope of the course and exam. Exam questions read a file with one style or the other, never both. Spend your time on the .hasNext() loop instead.
8Complete Example — Filter Data from a File
Read comma-delimited data from a file, parse it, and collect matching entries.
public static ArrayList<String> getHighScorers(String filename)
throws IOException
{
Scanner reader = new Scanner(new File(filename));
ArrayList<String> result = new ArrayList<String>();
while (reader.hasNext())
{
String line = reader.nextLine();
String[] parts = line.split(",");
String name = parts[0];
int score = Integer.parseInt(parts[1]);
if (score >= 90)
{
result.add(name);
}
}
reader.close();
return result;
}
Each line looks like Son,95. The method returns only the names with scores ≥ 90.
9Common File-Reading Algorithms
Almost every file question on the exam is one of these four shapes. Each assumes reader is an open Scanner and the enclosing method declares throws IOException.
9.1 Sum or Total the Numbers
int total = 0;
while (reader.hasNext())
{
total += reader.nextInt();
}
reader.close();
The accumulator starts at 0 outside the loop, never inside it. Declaring total inside the body would reset it every pass and leave only the last value.
9.2 Count the Lines That Match a Condition
int count = 0;
while (reader.hasNext())
{
String line = reader.nextLine();
if (line.length() > 10)
{
count++;
}
}
reader.close();
Store the line in a variable before testing it. Calling reader.nextLine() inside the if condition and again in the body reads two different lines and silently skips data.
9.3 Track a Maximum
int max = reader.nextInt(); // seed with the first value
while (reader.hasNext())
{
int value = reader.nextInt();
if (value > max)
{
max = value;
}
}
reader.close();
Starting max at 0 is a classic wrong answer: if every number in the file is negative, the method reports 0 — a value that is not in the file at all. Seeding with the first value avoids that. It does assume the file is not empty, which exam questions will tell you.
9.4 Build a List from a File
ArrayList<String> names = new ArrayList<String>();
while (reader.hasNext())
{
names.add(reader.nextLine());
}
reader.close();
This is the bridge between this topic and the rest of Unit 4: once the data is in an ArrayList, every traversal, search and sort you already know applies unchanged.
Open a Scanner on a File, loop on .hasNext(), read one unit per pass, close when done. Only the middle line differs between these four algorithms. If you can write the skeleton from memory, the rest is ordinary Unit 4 work.
10Summary
| Class | Method | Key point |
|---|---|---|
File | File(String) | Constructor only. Just a path reference — doesn't open the file. |
Scanner | Scanner(File f) | Opens a file for reading. Requires throws IOException. |
.nextInt() | Reads one int | |
.nextDouble() | Reads one double | |
.nextBoolean() | Reads one boolean | |
.nextLine() | Reads the rest of the current line as a String | |
.next() | Reads one token (whitespace-delimited) | |
.hasNext() | Returns true if more data exists | |
String | .split(String del) | Breaks a line into a String[] by delimiter |
Integer | .parseInt(String) | Converts String to int |
Double | .parseDouble(String) | Converts String to double |
On the AP exam, file I/O is intentionally simple: create a File, open it with Scanner, loop with .hasNext(), read with .nextLine() or .nextInt(), parse with .split() and Integer.parseInt(), and close. No writing to files, no PrintWriter, no try/catch.