Topic 4.6 Notes – Using Text Files
1. What Text Files Are and Why They Matter
A file is persistent storage. That means the data still exists after your program finishes running.
- Variables / arrays → live in memory, disappear when program ends
- Files → stored on disk, still there tomorrow
A text file contains readable characters. You can open it in Notepad or any text editor.
Your variables and arrays exist in memory (RAM). When the program stops, that memory is cleared. Files are stored on the disk, which is why they remain after the program ends.
Programs read files to:
- Process large datasets
- Load saved information
- Analyze stored values
For AP, you are not writing files. You only need to know how to read them.
2. Setting Up File Input Correctly
There’s a specific pattern you’ll see again and again.
Required Imports
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
FileandIOExceptioncome fromjava.ioScannercomes fromjava.util
If you forget these, it won’t compile.
Create the File Object
File dataFile = new File("data.txt");
This does not read the file yet.
It just creates an object representing the file’s path.
Handle IOException
Java forces you to acknowledge that file access might fail.
The AP-style solution:
public static void main(String[] args) throws IOException
If the file doesn’t exist, the program stops. That’s fine for AP.
Connect Scanner to the File
Scanner input = new Scanner(dataFile);
Now you can use familiar Scanner methods.
Always Close the File
input.close();
Closing the Scanner closes the file. Expect to lose points if you forget this on an FRQ.
3. Scanner Methods You Must Know
These work exactly like Scanner with keyboard input.
Token-Based Reading
next()→ next wordnextInt()→ next integernextDouble()→ next doublenextBoolean()→ next boolean
If the next token isn’t the expected type, Java throws an InputMismatchException.
Line-Based Reading
nextLine()→ returns the entire next line
Be aware:
nextLine()behaves differently with whitespace.- Mixing
nextLine()withnextInt()can cause empty strings.
The AP exam does not require complex mixing situations, but you should recognize why it might happen.
Checking Before Reading
These prevent crashes:
hasNext()hasNextInt()hasNextDouble()
Example loop pattern:
while (input.hasNextInt()) {
int value = input.nextInt();
}
This runs until the file runs out of integers.
That while (input.hasNext___()) pattern is the key idea.
4. Processing File Data with Algorithms
Once you read the data, it becomes a normal loop problem.
Counting Pattern
int count = 0;
while (input.hasNext()) {
input.next();
count++;
}
Sum and Average Pattern
int sum = 0;
int count = 0;
while (input.hasNextInt()) {
int num = input.nextInt();
sum += num;
count++;
}
double average = (double) sum / count;
This shows up constantly on tests.
Storing in an ArrayList
ArrayList<Integer> numbers = new ArrayList<>();
while (input.hasNextInt()) {
numbers.add(input.nextInt());
}
Very common FRQ move:
- Read values
- Store in
ArrayList - Process later
Reading Structured Data
If a file looks like:
Liam 84
Maya 91
You’d read it like:
while (input.hasNext()) {
String name = input.next();
int score = input.nextInt();
}
You must trust the file format matches your reading pattern.
Using split
If you read a whole line:
String line = input.nextLine();
String[] parts = line.split(" ");
split(" ") breaks the line at spaces and returns a String[].
You are not expected to use complex regular expressions.
5. Common Exam Mistakes
- Forgetting
throws IOException - Forgetting
input.close() - Using
hasNext()when reading only integers - Calling
nextInt()without checkinghasNextInt() - Mixing
nextLine()andnextInt()incorrectly
A subtle one: using while (input.hasNext()) but calling nextInt() inside. If the next token isn’t an int, it crashes.
On the AP exam, they often give you the file setup and expect you to focus on the loop logic. Treat file input like array traversal. Same patterns. Same algorithm thinking.