# AP® Computer Science A 4.6 Using Text Files

Source: https://lockincs.com/ap-csa/unit-4/4-6-using-text-files/  
Last reviewed against the College Board Course and Exam Description (CED): 2026-11-12  
CED codes: 4.6.A, 4.6.A.1, 4.6.A.2, 4.6.A.3, 4.6.A.4, 4.6.A.5, 4.6.A.6, 4.6.A.7, 4.6.A.8, 4.6.A.9, 4.6.A.10

A file stores data that persists when the program is not running, and a program connects to it with the File and Scanner classes from java.io and java.util. The method that opens the file must say what happens if it cannot be opened, for example with throws IOException. Then a while loop with hasNext reads the data using Scanner methods such as nextInt, next and nextLine, and close ends the connection.

## What you will learn

- 4.6.A Develop code to read data from a text file.

## 1\. Files and the classes that open them

A file is storage for data that persists when the program is not running, and a program can retrieve that data while it runs 4.6.A.1. A variable disappears when the program ends; a file such as `scores.txt` stays on the disk.

A file is connected to a program with two classes: `File` and `Scanner` 4.6.A.2. You open a file by creating a `File` object, with the file name as the argument of the constructor `File(String str)`, where `str` is the pathname of the file 4.6.A.3. Then you pass that `File` to the `Scanner(File f)` constructor, which creates a `Scanner` that reads from it 4.6.A.6.

| Step | Code | What it does |
| --- | --- | --- |
| 1\. Name the file | `File f = new File("scores.txt");` | Connects a `File` object to the file name |
| 2\. Make a reader | `Scanner input = new Scanner(f);` | A `Scanner` that reads from that file |
| 3\. Read | `input.nextInt()`, `input.next()`, … | Returns the next piece of data |
| 4\. Close | `input.close();` | Ends the connection |

`File` and `IOException` are in the `java.io` package, so an `import` statement must make them available 4.6.A.5. `Scanner` is in `java.util`, so it needs an import too.

## 2\. throws IOException

When you use the `File` class, Java requires you to say what to do if the file with that name cannot be opened. One way is to add `throws IOException` to the header of the method that uses the file 4.6.A.4. If the file name is invalid, the program then terminates 4.6.A.4.

The data file used in this section, `scores.txt`:

```
12 7 25
9 14
30
```

A complete program that reads the first two numbers:

```
import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class FirstScores
{
    public static void main(String[] args) throws IOException
    {
        File f = new File("scores.txt");
        Scanner input = new Scanner(f);

        int a = input.nextInt();
        int b = input.nextInt();
        System.out.println(a + b);

        input.close();
    }
}
```

Output:

```
19
```

Real view: forget `throws IOException` and the code does not compile.

```
import java.io.File;
import java.util.Scanner;

public class NoThrows
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(new File("scores.txt"));
        System.out.println(input.nextInt());
        input.close();
    }
}
```

Compiler error:

```
error: unreported exception FileNotFoundException; must be caught or declared to be thrown
```

A `FileNotFoundException` is a kind of `IOException`, which is why `throws IOException` covers it. Forget the import for `File` and you get a different compiler error:

```
import java.io.IOException;
import java.util.Scanner;

public class NoImport
{
    public static void main(String[] args) throws IOException
    {
        Scanner input = new Scanner(new File("scores.txt"));
        input.close();
    }
}
```

Compiler error:

```
error: cannot find symbol
```

With everything correct but a file name that does not exist (here `score.txt`, a typo), the program compiles and then terminates when it runs:

```
import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class Typo
{
    public static void main(String[] args) throws IOException
    {
        Scanner input = new Scanner(new File("score.txt"));
        System.out.println("opened");
        input.close();
    }
}
```

Output:

```
Exception in thread "main" java.io.FileNotFoundException: score.txt (No such file or directory)
```

“opened” is never printed. (On some operating systems the message in brackets is worded differently.)

## 3\. Scanner methods

These `Scanner` methods are in the Java Quick Reference 4.6.A.6. A **token** is a piece of text separated from the next one by whitespace (spaces, tabs or line breaks).

| Method | Returns | If it goes wrong |
| --- | --- | --- |
| `int nextInt()` | the next `int` | `InputMismatchException` if the next token is not an `int` or is out of range |
| `double nextDouble()` | the next `double` | `InputMismatchException` if the next token is not a `double` |
| `boolean nextBoolean()` | the next `boolean` (`true` or `false`) | `InputMismatchException` if it is not a `boolean` |
| `String next()` | the next token as a `String` |  |
| `String nextLine()` | the rest of the current line as a `String` (can be the empty string right after another `Scanner` method) |  |
| `boolean hasNext()` | `true` if there is another item to read, `false` otherwise |  |
| `void close()` | nothing; closes the scanner |  |

The data file `teams.txt`, one team per line (name, wins, average goals, qualified):

```
Lions 3 4.5 true
Hawks 1 2.0 false
```

```
import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class Teams
{
    public static void main(String[] args) throws IOException
    {
        Scanner input = new Scanner(new File("teams.txt"));

        String name = input.next();
        int wins = input.nextInt();
        double avg = input.nextDouble();
        boolean qualified = input.nextBoolean();

        System.out.println(name + " won " + wins + " games");
        System.out.println("Average goals: " + avg);
        System.out.println("Qualified: " + qualified);
        System.out.println("Next team: " + input.next());

        input.close();
    }
}
```

Output:

```
Lions won 3 games
Average goals: 4.5
Qualified: true
Next team: Hawks
```

Notice that the line break after `true` does not matter to `next()`: it is just whitespace between tokens.

When a token does not match the method, the program stops with an `InputMismatchException` 4.6.A.6. The file `laps.txt` contains `8 5 abc 4`:

```
import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class Laps
{
    public static void main(String[] args) throws IOException
    {
        Scanner input = new Scanner(new File("laps.txt"));
        int total = 0;
        while (input.hasNext())
        {
            total += input.nextInt();
            System.out.println("Total so far: " + total);
        }
        input.close();
    }
}
```

Output:

```
Total so far: 8
Total so far: 13
Exception in thread "main" java.util.InputMismatchException
```

`hasNext()` was `true` (the token `abc` exists), but `nextInt()` cannot turn it into an `int`.

**Background:** keyboard input is outside the scope of the AP® Computer Science A course and exam 4.6.A.6. Also, `nextLine` handles whitespace differently from the other methods, so mixing `nextLine` with `nextInt`, `next` and the others on the same file sometimes needs extra code to adjust 4.6.A.7. Writing or analyzing code that mixes them is outside the scope of the exam 4.6.A.7. A safe rule: either read tokens (`next`, `nextInt`, …) or read whole lines (`nextLine`), not both.

## 4\. Reading until the end with hasNext

A `while` loop can keep reading as long as the file still contains items, using `hasNext` as the loop condition 4.6.A.9. This is the standard file traversal:

```
import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class SumScores
{
    public static void main(String[] args) throws IOException
    {
        Scanner input = new Scanner(new File("scores.txt"));
        int sum = 0;
        int count = 0;

        while (input.hasNext())
        {
            int s = input.nextInt();
            sum += s;
            count++;
        }
        input.close();

        System.out.println(count + " scores, sum " + sum);
        System.out.println("Average: " + (double) sum / count);
    }
}
```

Output:

```
6 scores, sum 97
Average: 16.166666666666668
```

The numbers were on three lines in `scores.txt`, but the loop does not care: it reads token after token until `hasNext()` returns `false`. Calling `nextInt()` again after that would throw a `NoSuchElementException`.

When you are finished with the file, close it with the `close` method from `Scanner` 4.6.A.10. Closing releases the file for other programs and makes clear the reading is over.

## 5\. Reading lines and splitting them

Many data files store one record per line, with the values separated by commas. Read each whole line with `nextLine()` and break it into parts with the `String` method `split` 4.6.A.8: `String[] split(String del)` returns a `String` array where each element is a substring of the original, split around matches of `del` 4.6.A.8.

The data file `roster.txt`:

```
Ana,12,true
Ben,9,false
Cleo,15,true
```

```
import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class Roster
{
    public static void main(String[] args) throws IOException
    {
        Scanner input = new Scanner(new File("roster.txt"));

        while (input.hasNext())
        {
            String line = input.nextLine();
            String[] parts = line.split(",");
            System.out.println(parts[0] + " has " + parts.length + " fields; points = " + parts[1]);
        }
        input.close();
    }
}
```

Output:

```
Ana has 3 fields; points = 12
Ben has 3 fields; points = 9
Cleo has 3 fields; points = 15
```

For the line `"Ana,12,true"`, `split(",")` gives this array:

| index | 0 | 1 | 2 |
| --- | --- | --- | --- |
| `parts` | “Ana” | “12” | “true” |

Every element is a `String`, even `"12"`. To do arithmetic with it, convert it with `Integer.parseInt` (topic 4.7).

```
String date = "2026 11 12";
String[] pieces = date.split(" ");
System.out.println(pieces.length);
System.out.println(pieces[1] + pieces[2]);
```

Output:

```
3
1112
```

`pieces[1] + pieces[2]` joins two strings, so the result is `1112`, not 23.

**Background:** the `del` argument is a regular expression, a pattern language. Some characters such as `.` and `*` have special meanings in it. Code that uses those special properties is outside the scope of the AP® exam 4.6.A.8, so on the exam expect simple separators like `","`, `" "` or `":"`.

## Common mix-ups

- Not true: new File("data.txt") reads the data. A File object only names the file to open. You pass it to the Scanner constructor, and the Scanner methods do the reading.
- Not true: If the file is missing, the program just reads nothing. If the file cannot be opened, an exception is thrown and, with throws IOException in the header, the program terminates.
- Not true: next() returns the next line. next() returns the next token, a piece of text up to the next whitespace. nextLine() returns the rest of the line as one String.
- Not true: File and Scanner are always available, like String. File and IOException are in java.io and Scanner is in java.util, so each needs an import statement. String and Math are in java.lang, which needs no import.

## In 30 seconds

- A file stores data that persists after the program ends; a program can read it while running.
- Connect with new File(name) and new Scanner(file); import java.io.File, java.io.IOException and java.util.Scanner.
- Add throws IOException to the header of the method that uses the file; an invalid file name terminates the program.
- nextInt, nextDouble, nextBoolean and next read one token; nextLine reads a line; the wrong type throws an InputMismatchException.
- while (input.hasNext()) reads until the file has no more items; split breaks a line into a String array.
- Call close() when finished with the file.

## Checkpoint: 5 practice questions

### Question 1

The following method does not compile. Assume `java.io.File`, `java.io.IOException` and `java.util.Scanner` are imported. Which change allows the method to compile?

```java
public static int readFirst(String name)
{
    Scanner sc = new Scanner(new File(name));
    int first = sc.nextInt();
    sc.close();
    return first;
}
```

- A. Change `sc.nextInt()` to `sc.next()`
- B. Add `throws IOException` to the method header
- C. Remove the call `sc.close()`
- D. Change the return type from `int` to `void`

**Answer: B.** When a method uses a file, Java requires it to say what happens if the file cannot be opened; adding `throws IOException` to the header does that. The reading method, the call to `close` and the return type are not the cause; changing them still leaves the unreported exception (and `next` or `void` would add new compile errors).

### Question 2

**nums.txt**

| Line | Contents |
| --- | --- |
| 1 | 4 7 |
| 2 | 2 9 |

The file nums.txt contains the data shown. Consider the following code segment, which appears in a method with `throws IOException` in its header. What is printed?

```java
Scanner in = new Scanner(new File("nums.txt"));
int total = 0;
while (in.hasNext())
{
    int n = in.nextInt();
    if (n % 2 == 1)
    {
        total += n;
    }
}
in.close();
System.out.println(total);
```

- A. 22
- B. 6
- C. 2
- D. 16

**Answer: D.** The `while` loop uses `hasNext` to read every token, across both lines, and adds only the odd values: 7 + 9 = 16. 22 adds every value, 6 adds the even values (4 + 2), and 2 is the number of odd values, not their sum.

### Question 3

**mix.txt**

| Line | Contents |
| --- | --- |
| 1 | 5 2.5 7 |

The file mix.txt contains the single line shown. Consider the following code segment, which appears in a method with `throws IOException` in its header. What is the result of executing the code segment?

```java
Scanner in = new Scanner(new File("mix.txt"));
int a = in.nextInt();
int b = in.nextInt();
System.out.println(a + b);
in.close();
```

- A. 7 is printed
- B. 7.5 is printed
- C. An `InputMismatchException` is thrown
- D. 12 is printed

**Answer: C.** The first `nextInt()` reads 5. The second `nextInt()` finds the token 2.5, which is not an `int`, so it throws an `InputMismatchException`. "7" assumes 2.5 is truncated to 2, "7.5" assumes it is read as a `double`, and "12" skips 2.5 and reads 7.

### Question 4

Consider the following code segment. What is printed as a result of executing the code segment?

```java
String rec = "Oslo:12:true";
String[] p = rec.split(":");
System.out.println(p.length + p[1]);
```

- A. 312
- B. 15
- C. 3 12
- D. 4

**Answer: A.** `split(":")` returns the array {"Oslo", "12", "true"}, so `p.length` is 3 and `p[1]` is the `String` "12". An `int` plus a `String` is concatenation, giving "312". "15" treats "12" as a number, "3 12" adds a space that is not in the code, and "4" miscounts the pieces.

### Question 5

**city.txt**

| Line | Contents |
| --- | --- |
| 1 | New York 8 |

The file city.txt contains the single line shown. Consider the following code segment, which appears in a method with `throws IOException` in its header. What is printed?

```java
Scanner in = new Scanner(new File("city.txt"));
String a = in.next();
String b = in.next();
in.close();
System.out.println(b);
```

- A. New York
- B. York
- C. 8
- D. New

**Answer: B.** `next()` returns one token, stopping at whitespace. The first call returns "New" and the second returns "York", which is printed. "New York" treats two words as one token (`nextLine()` would return the whole line "New York 8"), "8" is the third token, and "New" is the first token, stored in `a`.

## Questions students ask

**How do you read a text file in Java for AP® Computer Science A?**

Import java.io.File, java.io.IOException and java.util.Scanner, add throws IOException to the method header, create Scanner input = new Scanner(new File("name.txt")), read in a while (input.hasNext()) loop, then call input.close().

**Why do I need throws IOException?**

Java requires you to say what happens if the file cannot be opened. Adding throws IOException to the method header is one way; if the file name is invalid, the program then terminates with an exception.

**What is the difference between next() and nextLine()?**

next() returns the next token, stopping at whitespace. nextLine() returns everything up to the end of the line. On the AP® exam you will not mix nextLine with the other Scanner methods on the same file.

**What does split do?**

split(del) returns a String array of the pieces of a String between the matches of del. For example "a,b,c".split(",") gives the array {"a", "b", "c"}.

**Is keyboard input on the AP® exam?**

No. Accepting input from the keyboard is outside the scope of the course and exam. Scanner is used to read from a file.

---

© LockInCS, licensed CC BY-NC-ND 4.0. AP® is a trademark registered by the College Board, which is not affiliated with, and does not endorse, this website.
