AP CSA File Scanner I/O
File I/O with Scanner New in 2026
Reading data from external files is a brand-new topic in the 2025-2026 AP CSA curriculum. The Scanner class (combined with File) lets a Java program read text data from a file line by line or token by token. This skill appears in MCQ and may appear in FRQs.
Exam Relevance: File I/O with Scanner is new to the 2025-2026 AP CSA course. Expect questions on constructing a Scanner from a File, reading with hasNextLine() / nextLine(), handling FileNotFoundException, and common traps like consuming a newline with nextInt().
Required Imports
import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException; // or java.io.IOException
These must appear at the top of any class that uses Scanner with files. On the AP exam, the question will specify which imports are provided.
Creating a Scanner for File Input
To read from a file, pass a File object to the Scanner constructor. This always requires handling a checked exception because the file might not exist.
Pattern 1 — try-catch block
try
{
Scanner sc = new Scanner(new File("data.txt"));
while (sc.hasNextLine())
{
String line = sc.nextLine();
System.out.println(line);
}
sc.close();
}
catch (FileNotFoundException e)
{
System.out.println("File not found: " + e.getMessage());
}
Pattern 2 — throws declaration (propagates exception)
public static void readFile() throws IOException
{
Scanner sc = new Scanner(new File("scores.txt"));
while (sc.hasNextLine())
{
String line = sc.nextLine();
// process line
}
sc.close();
}
Scanner Reading Methods
| Method | What it reads | Consumes newline? |
|---|---|---|
nextLine() |
Entire line up to (and including) \n | Yes |
next() |
Next whitespace-delimited token | No |
nextInt() |
Next token as int
|
No |
nextDouble() |
Next token as double
|
No |
hasNextLine() |
Returns true if another line exists |
N/A |
hasNext() |
Returns true if another token exists |
N/A |
hasNextInt() |
Returns true if next token is a valid int
|
N/A |
Reading a File Line by Line
Scanner sc = new Scanner(new File("names.txt"));
while (sc.hasNextLine())
{
String name = sc.nextLine();
System.out.println("Hello, " + name + "!");
}
sc.close();
If names.txt contains:
Alice Bob Carol
Output:
Hello, Alice! Hello, Bob! Hello, Carol!
Reading Mixed Data Types
When a file contains numbers and text on the same line, read tokens individually with next() and nextInt() etc.
// File contents: "Alice 95\nBob 87\nCarol 91"
Scanner sc = new Scanner(new File("grades.txt"));
while (sc.hasNextLine())
{
String name = sc.next(); // reads next token
int score = sc.nextInt(); // reads next integer token
System.out.println(name + ": " + score);
if (sc.hasNextLine()) {
sc.nextLine(); // consume remaining newline
}
}
sc.close();
The nextInt() + nextLine() Trap
This is the most common bug in file-reading code. When you call nextInt(), it reads the integer but leaves the newline character in the buffer. A subsequent nextLine() will read that empty newline instead of the next actual line.
// WRONG: nextLine() reads the leftover newline, not "Alice" int count = sc.nextInt(); String name = sc.nextLine(); // reads "" (the leftover newline) // CORRECT: consume the leftover newline first int count = sc.nextInt(); sc.nextLine(); // consumes the leftover newline String name = sc.nextLine(); // now reads "Alice" correctly
Exam Trap: Questions that mix nextInt() (or nextDouble()) with nextLine() almost always target this exact bug. The fix is always to call sc.nextLine() immediately after the numeric read to consume the leftover newline.
Always Close the Scanner
Call sc.close() after you are done reading. This releases the file handle. On the exam, code that never closes the Scanner is technically a resource leak, but it will not cause a compile-time or runtime error in most questions.
Handling FileNotFoundException
catch (FileNotFoundException e)
{
System.out.println("File not found.");
}
FileNotFoundException is a checked exception — the compiler requires you to handle it (try-catch) or declare it (throws). Unlike runtime exceptions such as NullPointerException, it cannot be ignored.
Checked vs. Unchecked: FileNotFoundException is checked — you must handle it. ArrayIndexOutOfBoundsException and NullPointerException are unchecked — the compiler does not require handling.
Complete Example — Count Lines in a File
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class LineCounter
{
public static int countLines(String filename) throws FileNotFoundException
{
Scanner sc = new Scanner(new File(filename));
int count = 0;
while (sc.hasNextLine())
{
sc.nextLine();
count++;
}
sc.close();
return count;
}
}
Practice MCQs
Consider the following code segment. Assume data.txt exists and contains three lines of text.Scanner sc = new Scanner(new File("data.txt"));while (sc.hasNextLine()) sc.nextLine();
Which of the following best describes a problem with this code?
- (A) It will throw a
NullPointerExceptionbecausescis not initialized. - (B) It will produce a compile error because
FileNotFoundExceptionis not handled. - (C) It will only read the first line of the file.
- (D) It reads all lines but never closes the Scanner, creating a resource leak.
A file named scores.txt contains:5Alice
Consider the following code:Scanner sc = new Scanner(new File("scores.txt"));int n = sc.nextInt();String name = sc.nextLine();
What is stored in name after this code executes?
- (A)
"Alice" - (B)
"5" - (C)
""(empty string) - (D) The code throws a
NoSuchElementException.
Which of the following code segments correctly reads all integers from a file named nums.txt and computes their sum? Assume FileNotFoundException is handled by the caller.
- (A)
Scanner sc = new Scanner("nums.txt");while (sc.hasNextInt()) sum += sc.nextInt(); - (B)
Scanner sc = new Scanner(new File("nums.txt"));while (sc.hasNextInt()) sum += sc.nextInt(); - (C)
Scanner sc = new Scanner(new File("nums.txt"));while (sc.hasNextLine()) sum += sc.nextInt(); - (D)
Scanner sc = new Scanner(new File("nums.txt"));while (sc.hasNext()) sum += sc.nextLine();
Which statement about FileNotFoundException is NOT accurate?
- (A) It is a subclass of
IOException. - (B) It is a checked exception that must be caught or declared.
- (C) It can be thrown when calling
new Scanner(new File(filename)). - (D) It will be thrown at runtime whenever an array index is out of bounds.
Common Mistakes
-
Passing a String instead of a File:
new Scanner("data.txt")reads the string "data.txt", not the file. Always usenew Scanner(new File("data.txt")). -
Ignoring the checked exception:
Scanner(File)throwsFileNotFoundException. Forgetting to handle it is a compile error. -
nextInt() + nextLine() mismatch: Call
sc.nextLine()after any numeric read to consume the leftover newline before callingnextLine(). -
Not closing the Scanner: Always call
sc.close()when done. On the AP exam this is considered best practice. -
Using wrong check method: If the file might have non-integer lines, use
hasNextInt()nothasNextLine()before callingnextInt().
Quick Reference
| Task | Code |
|---|---|
| Open a file | Scanner sc = new Scanner(new File("file.txt")); |
| Read all lines | while (sc.hasNextLine()) { String s = sc.nextLine(); } |
| Read all integers | while (sc.hasNextInt()) { int n = sc.nextInt(); } |
| Handle exception | try { ... } catch (FileNotFoundException e) { ... } |
| Close scanner | sc.close(); |
Related Topics
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.
tanner@apcsexamprep.com
Courses
AP CSA, CSP, & Cybersecurity
Response Time
Within 24 hours
Prefer email? Reach me directly at tanner@apcsexamprep.com