---
title: "AP CSA Text Files: File and Scanner"
description: "Review AP CSA text files for Topic 4.6: File, Scanner, throws IOException, hasNext loops, nextInt, nextDouble, nextLine, split, and closing files."
canonical: "https://fiveable.me/ap-comp-sci-a/unit-4/using-text-files/study-guide/JhiQXb5r4daUivzP1Xkm"
type: "study-guide"
subject: "AP Computer Science A"
unit: "Unit 4 – Data Collections"
lastUpdated: "2026-06-07"
---

# AP CSA Text Files: File and Scanner

## Summary

Review AP CSA text files for Topic 4.6: File, Scanner, throws IOException, hasNext loops, nextInt, nextDouble, nextLine, split, and closing files.

## Guide

## TLDR
Reading a text [file](/ap-comp-sci-a/key-terms/file "fv-autolink") in [AP Computer Science A](/ap-comp-sci-a "fv-autolink") 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](/ap-comp-sci-a/unit-1/why-programming-why-java/study-guide/lVK6rmrBuug17i1Hna9z "fv-autolink") 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](/ap-comp-sci-a/unit-4/developing-algorithms-using-arraylists/study-guide/MKbteieYvLOpWIwfqiND "fv-autolink"), and loop work in the rest of [Unit 4](/ap-comp-sci-a/unit-4 "fv-autolink"). 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 `File` object with the file name, then passing that `File` to a `Scanner` [constructor](/ap-comp-sci-a/unit-1/creating-and-storing-objects/study-guide/rUOTKl6Ih5noXJ0GtxJF "fv-autolink").
- The `File` and `IOException` classes come from `java.io`, and `Scanner` comes from `java.util`, so you must import them.
- Because opening a file can fail, the method that uses the file needs `throws IOException` in its header; if the file name is invalid, the program terminates.
- Use a `while` loop with `hasNext` as the condition to keep reading while data remains, and call `close` when you are done.
- Scanner methods like `nextInt`, `nextDouble`, `nextBoolean`, `next`, and `nextLine` each read a specific kind of value, and a type mismatch causes an `InputMismatchException`.

## Files: Data That Persists

A file is storage for data that stays around even when your program is not running. [Variables](/ap-comp-sci-a/unit-1/expressions-and-assignment-statements/study-guide/01dr6uUPDAn3SjtK2Psr "fv-autolink") 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](/ap-comp-sci-a/unit-4/ethical-and-social-implications/study-guide/iec7yzDQ2qENx5UAdiPJ "fv-autolink") 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](/ap-comp-sci-a/key-terms/argument "fv-autolink") 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](/ap-comp-sci-a/key-terms/package "fv-autolink"), so you need import statements to use them. A common setup looks like this:

```java
import 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](/ap-comp-sci-a/unit-1/14-assignment-statement-input/study-guide/compoundassignment "fv-autolink") source.

These Scanner methods and the constructor are part of the Java Quick [Reference](/ap-comp-sci-a/key-terms/reference "fv-autolink") 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](/ap-comp-sci-a/unit-1/casting-and-ranges-of-variables/study-guide/kW3XXEIwJwVRXFx3ntdC "fv-autolink"), it results in an `InputMismatchException`.
- `double nextDouble()`: returns the next double read from the file. If the next double does not exist, it results in an `InputMismatchException`.
- `boolean nextBoolean()`: returns the next [boolean](/ap-comp-sci-a/unit-1/variables-and-primitive-data-types/study-guide/rezA6f3hJz84TKaY5Jjl "fv-autolink") read from the file. If the next boolean does not exist, it results in an `InputMismatchException`.
- `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](/ap-comp-sci-a/key-terms/loop-condition "fv-autolink"). When you are finished, call `close` to close the file.

Here is the basic pattern that ties it all together:

```java
import 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:

```java
import 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](/ap-comp-sci-a/unit-2/developing-algorithms-using-strings/study-guide/hDOL1VhnMQFPkBf6xMMW "fv-autolink") of this String, split around matches of the given [expression](/ap-comp-sci-a/key-terms/expression "fv-autolink") `del`.

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](/ap-comp-sci-a/key-terms/algorithm "fv-autolink") 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](/ap-comp-sci-a/key-terms/data-type "fv-autolink") 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 `File` object does not read or load the file by itself. It just represents the file name. The reading happens through the `Scanner`.
- `throws IOException` is 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.
- `hasNext` and `next` are not the same thing. `hasNext` returns a boolean that tells you whether more data exists, while `next` actually reads and returns the next token. Use `hasNext` as the loop condition and `next` (or another read method) inside the loop.
- Forgetting `close` does 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 `nextLine` with token methods like `nextInt` on the same input can cause whitespace problems, and combining them on the same source is outside the [scope](/ap-comp-sci-a/unit-3/scope-and-access/study-guide/56FUK4RSofr7slzwm6xm "fv-autolink") of this course and exam, so you will not be tested on that mix.

## Related AP Computer Science A Guides

- [4.4 Traversing Arrays](/ap-comp-sci-a/unit-4/traversing-arrays/study-guide/kRcOqfawCcBz6gcT646t)
- [4.5 Developing Algorithms Using Arrays](/ap-comp-sci-a/unit-4/developing-algorithms-using-arrays/study-guide/c6dpJfmjG7oVFDqnXFAk)
- [4.14 Searching](/ap-comp-sci-a/unit-4/searching/study-guide/8PTb7wMUSzHeI7aTUFNy)
- [4.11 2D Arrays](/ap-comp-sci-a/unit-4/2d-arrays/study-guide/5WDx6ZFeWhx2aVuiZI6R)
- [4.13 Implementing 2D Array Algorithms](/ap-comp-sci-a/unit-4/implementing-2d-array-algorithms/study-guide/9ucC5cB6ffrLnA4b3FU3)
- [4.1 Ethical and Social Implications](/ap-comp-sci-a/unit-4/ethical-and-social-implications/study-guide/iec7yzDQ2qENx5UAdiPJ)

## Vocabulary

- **File class**: A Java class used to create a File object that connects a program to a text file for reading data.
- **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.
- **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.
- **Scanner class**: A Java class used to obtain and parse text input from the keyboard or other input sources.
- **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.
- **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.
- **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.
- **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.

## FAQs

### 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.

## Structured Data

```json
{"@context":"https://schema.org","@type":"FAQPage","inLanguage":"en","mainEntity":[{"@type":"Question","@id":"https://fiveable.me/ap-comp-sci-a/unit-4/using-text-files/study-guide/JhiQXb5r4daUivzP1Xkm#how-do-you-read-text-files-in-ap-csa","name":"How do you read text files in AP CSA?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","@id":"https://fiveable.me/ap-comp-sci-a/unit-4/using-text-files/study-guide/JhiQXb5r4daUivzP1Xkm#which-imports-do-i-need-for-ap-csa-text-files","name":"Which imports do I need for AP CSA text files?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","@id":"https://fiveable.me/ap-comp-sci-a/unit-4/using-text-files/study-guide/JhiQXb5r4daUivzP1Xkm#why-does-file-reading-code-use-throws-ioexception","name":"Why does file-reading code use throws IOException?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","@id":"https://fiveable.me/ap-comp-sci-a/unit-4/using-text-files/study-guide/JhiQXb5r4daUivzP1Xkm#what-does-hasnext-do-when-reading-a-file","name":"What does hasNext do when reading a file?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","@id":"https://fiveable.me/ap-comp-sci-a/unit-4/using-text-files/study-guide/JhiQXb5r4daUivzP1Xkm#what-is-the-difference-between-next-and-nextline","name":"What is the difference between next and nextLine?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","@id":"https://fiveable.me/ap-comp-sci-a/unit-4/using-text-files/study-guide/JhiQXb5r4daUivzP1Xkm#what-does-split-do-in-ap-csa-text-file-problems","name":"What does split do in AP CSA text-file problems?","acceptedAnswer":{"@type":"Answer","text":"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."}}]}
```
