TLDR
Reading a text file in AP Computer Science A means connecting a File object to a Scanner, then pulling data out one piece at a time using Scanner methods like nextInt, next, and nextLine. Files store data that stays around after your program ends, so you can load real data sets and process them with the array and loop skills you already have. The main rules to remember: import the right classes, add throws IOException to your method header, loop with hasNext, and call close when you finish.

AP CSA Text Files
For AP CSA text files, the core pattern is File plus Scanner: create a File object with the file name, pass it into a Scanner, loop while hasNext() is true, read values with the correct Scanner method, and close the Scanner when you're done.
The AP exam can ask you to write or trace code that reads file data. Watch the details: import java.io.File, java.io.IOException, and java.util.Scanner; include throws IOException; and match the read method to the next value's type.
Why This Matters for the AP Computer Science A Exam
This topic is about developing code to read data from a text file, which connects file data to the array, ArrayList, and loop work in the rest of Unit 4. On the exam you can be asked to write code that reads from a file or to determine the result or output of code that reads from a file, so you need to know how the File and Scanner classes work together and what each Scanner method returns.
The skills tied to this topic are writing code that uses procedural abstractions like Scanner methods, predicting output from that code, and describing the conditions that must be met for file-reading code to work, such as the file existing and the method declaring throws IOException. Knowing the exact behavior of methods like hasNext, nextInt, and next helps you trace what a reading loop produces and spot when code will fail.
Key Takeaways
- A file stores data that persists after the program stops, and you retrieve that data during execution.
- Connect a file to your program by creating a
Fileobject with the file name, then passing thatFileto aScannerconstructor. - The
FileandIOExceptionclasses come fromjava.io, andScannercomes fromjava.util, so you must import them. - Because opening a file can fail, the method that uses the file needs
throws IOExceptionin its header; if the file name is invalid, the program terminates. - Use a
whileloop withhasNextas the condition to keep reading while data remains, and callclosewhen you are done. - Scanner methods like
nextInt,nextDouble,nextBoolean,next, andnextLineeach read a specific kind of value, and a type mismatch causes anInputMismatchException.
Files: Data That Persists
A file is storage for data that stays around even when your program is not running. Variables and arrays disappear when the program ends, but a file keeps its contents so you can read them back during a later run. This is what lets a program work with a real data set instead of only values typed directly into the code.
Reading a text file in Java uses two classes working together: File and Scanner. The File object represents the file you want to open, and the Scanner does the actual reading.
The File Class
You open a file by creating a File object and passing the file name as the argument to the constructor. The constructor File(String str) accepts a String file name to open for reading, where str is the pathname for the file.
The File class and the IOException class are both part of the java.io package, so you need import statements to use them. A common setup looks like this:
</>Javaimport java.io.File; import java.io.IOException; import java.util.Scanner;
Because opening a file can fail, Java requires you to indicate what to do if the file cannot be opened. One way is to add throws IOException to the header of the method that uses the file. If the file name is invalid, the program will terminate.
Reading with Scanner
To read from the file, pass the File object to a Scanner. The constructor Scanner(File f) accepts a File for reading. After that, you use the same Scanner methods you would use for any input source.
These Scanner methods and the constructor are part of the Java Quick Reference you get on the exam:
Scanner(File f): constructs a Scanner that reads from the given file.int nextInt(): returns the next int read from the file. If the next int does not exist or is out of range, it results in anInputMismatchException.double nextDouble(): returns the next double read from the file. If the next double does not exist, it results in anInputMismatchException.boolean nextBoolean(): returns the next boolean read from the file. If the next boolean does not exist, it results in anInputMismatchException.String nextLine(): returns the next line of text as a String. It can return the empty string if called immediately after another Scanner method reading from the same source.String next(): returns the next String read from the file.boolean hasNext(): returns true if there is a next item to read, and false otherwise.void close(): closes this scanner.
A while loop can detect whether the file still has elements to read by using hasNext as the loop condition. When you are finished, call close to close the file.
Here is the basic pattern that ties it all together:
</>Javaimport java.io.File; import java.io.IOException; import java.util.Scanner; public class FileReadingBasics { public static void main(String[] args) throws IOException { // Create File object using the file name File inputFile = new File("data.txt"); // Connect a Scanner to the file Scanner fileScanner = new Scanner(inputFile); // Keep reading while items remain while (fileScanner.hasNext()) { String token = fileScanner.next(); System.out.println("Read: " + token); } // Always close when done fileScanner.close(); } }
Reading numbers works the same way, just with the matching Scanner method:
</>Javaimport java.io.File; import java.io.IOException; import java.util.Scanner; public class NumericFileReading { public static void main(String[] args) throws IOException { File scoresFile = new File("scores.txt"); Scanner scanner = new Scanner(scoresFile); int count = 0; double sum = 0; double max = Double.MIN_VALUE; while (scanner.hasNext()) { double score = scanner.nextDouble(); sum += score; count++; if (score > max) { max = score; } } scanner.close(); if (count > 0) { double average = sum / count; System.out.println("Scores processed: " + count); System.out.println("Average: " + average); System.out.println("Maximum: " + max); } else { System.out.println("No scores found in file"); } } } // scores.txt contents: // 85.5 92.0 78.5 // 91.0 88.5 // 95.0 82.0 90.5
Splitting a Line into Pieces
Sometimes you read a whole line and then need to break it into parts. The String method split helps here, and it is part of the Java Quick Reference:
String[] split(String del): returns a String array where each element is a substring of this String, split around matches of the given expressiondel.
For example, if a line holds comma-separated values, you can split on a comma and then process each piece in the resulting array. This pairs naturally with the array work from earlier in Unit 4.
How to Use This on the AP Computer Science A Exam
Free Response
When a question hands you file-reading code, do not rewrite the setup. Recognize the pattern: create a File, build a Scanner from it, loop with hasNext, and read with the right method. Your job is usually to process the data into an array or ArrayList and apply an algorithm you already know, like finding a max, computing a sum, or counting items that match a property.
Make sure the method that touches the file declares throws IOException. If you are completing a provided method header that already has it, keep it.
Code Tracing
To predict output, walk through the loop one read at a time. Track what each call returns. next reads one token, nextInt reads one int, and hasNext checks whether anything is left. Picking the wrong method for the data in the file changes the result, so match the method to the value type.
Common Trap
If the data type you read does not match what is actually in the file, you get an InputMismatchException. For example, calling nextInt when the next token is a word will throw. Confirm the file's contents and use the matching Scanner method.
Common Misconceptions
- Creating a
Fileobject does not read or load the file by itself. It just represents the file name. The reading happens through theScanner. throws IOExceptionis required because opening a file can fail, not because of a problem in your algorithm. If the file name is invalid, the program terminates rather than silently continuing.hasNextandnextare not the same thing.hasNextreturns a boolean that tells you whether more data exists, whilenextactually reads and returns the next token. UsehasNextas the loop condition andnext(or another read method) inside the loop.- Forgetting
closedoes not always crash your program, but you should still close the Scanner when you finish reading, since closing a file when done is the expected practice. - Mixing
nextLinewith token methods likenextInton the same input can cause whitespace problems, and combining them on the same source is outside the scope of this course and exam, so you will not be tested on that mix.
Related AP Computer Science A Guides
Vocabulary
The following words are mentioned explicitly in the College Board Course and Exam Description for this topic.Term | Definition |
|---|---|
close() | A Scanner method that closes the scanner and the associated file when the program is finished using it. |
file | A storage location for data that persists when a program is not running and can be retrieved during program execution. |
File class | A Java class used to create a File object that connects a program to a text file for reading data. |
hasNext() | A Scanner method that returns true if there is another item to read in the file or input source, and false otherwise. |
import statement | A Java statement used to make classes from a package available for use in a program. |
InputMismatchException | An exception thrown when a Scanner method attempts to read a value that does not match the expected data type or is out of range. |
IOException | An exception class that is thrown when a file cannot be opened or read due to an invalid file name or I/O error. |
java.io package | A Java package containing classes like File and IOException that must be imported to use file input/output operations. |
next() | A Scanner method that returns the next String token read from a file or input source. |
nextBoolean() | A Scanner method that returns the next boolean value read from a file or input source. |
nextDouble() | A Scanner method that returns the next double value read from a file or input source. |
nextInt() | A Scanner method that returns the next integer value read from a file or input source. |
nextLine() | A Scanner method that returns the next line of text as a String read from a file or input source. |
Scanner class | A Java class used to obtain and parse text input from the keyboard or other input sources. |
split() | A String method that returns a String array by dividing a String into substrings based on a given delimiter expression. |
throws IOException | A method declaration clause that indicates the method may throw an IOException if a file cannot be opened. |
while loop | An iterative statement that repeatedly executes a block of code as long as a specified Boolean expression evaluates to true. |
whitespace | Blank characters such as spaces, tabs, and newlines that Scanner methods handle differently when reading from a file. |
Frequently Asked Questions
How do you read text files in AP CSA?
Create a File object with the file name, pass it to a Scanner, loop while hasNext() is true, read values with Scanner methods, and close the Scanner when done.
Which imports do I need for AP CSA text files?
You usually need import java.io.File, import java.io.IOException, and import java.util.Scanner to read a text file with File and Scanner.
Why does file-reading code use throws IOException?
Opening a file can fail if the file name is invalid or the file cannot be opened. Adding throws IOException indicates that the method may pass that exception upward.
What does hasNext do when reading a file?
hasNext() returns true if another item is available to read and false otherwise. It is commonly used as the condition in a while loop that reads a file.
What is the difference between next and nextLine?
next() reads the next token, while nextLine() reads the rest of the current line. The AP CSA CED notes that mixing nextLine with other Scanner methods on the same source is outside exam scope.
What does split do in AP CSA text-file problems?
split(String del) returns an array of substrings split around the delimiter. It is useful when a line contains multiple values, such as comma-separated data.