Reference Guide

From the College Board: This lesson aligns with AP CSA Unit 4, Topic 4.6: Using Text Files in the AP Computer Science A Course and Exam Description (College Board, 2025). The guide below summarizes the concepts in our own words.

Practice reading a file, choosing a reading method, and tracing how a loop consumes its contents.

Concept What to remember
File Represents a path; creating the object does not read the data.
Scanner(File) Opens a file for reading; handle opening errors, for example with throws IOException.
hasNext() / nextInt() Check for another token, then consume one integer token.
nextLine() / split(",") Read a whole line, then separate its fields.
close() Release the scanner’s resources when finished.

Jump to the lesson

Keep this guide open as you work through the examples and homework. Full references are also listed at the end of the lesson.

4.6 — Using Text Files

AP CSA · Unit 4: Data Collections

A school club has saved its attendance numbers. How can a Java program use those numbers tomorrow without someone typing them again?

Learning targets

By the end, you can connect a text file to a Scanner, choose the right reading method, trace a file-reading loop, and separate a simple delimited line into fields.

Before you start: variables, while loops, arrays, and String methods.

Try it: Predict the answer, record your work in your notes, and compare with a partner. Open each answer reveal after attempting the activity.

Warm-up: data that lasts

Imagine int attendance = 24; exists while your program runs. The program ends. Tomorrow it starts again.

  1. Does that variable automatically remember yesterday’s value?
  2. How would saving 24 in a text file help?
  3. Is a filename the same thing as the contents of a file?
Check your reasoning
  1. No. A local variable does not automatically preserve its value between program runs.
  2. The file can remain on storage after the program exits. A later run can read it.
  3. No. A filename/path tells Java where to look; the contents are the data stored there.

Read an attendance file

For optional execution, save this data as attendance.txt in your Java program’s working directory (the directory from which it runs). That is not always the folder containing the source file.

18 24
21 17

Save the complete program below as AttendanceReader.java.

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

public class AttendanceReader {
    public static void main(String[] args) throws IOException {
        File attendanceFile = new File("attendance.txt");
        Scanner input = new Scanner(attendanceFile);
        int total = 0;
        int days = 0;

        while (input.hasNext()) {
            int students = input.nextInt();
            total += students;
            days++;
        }
        input.close();

        System.out.println("Days: " + days);
        System.out.println("Total: " + total);
    }
}

Walk through it together:

  • File represents the path. Creating the File object does not create a missing file or read its contents.
  • Scanner opens that file for reading. Here we promise the file contains only valid integer tokens.
  • hasNext() checks whether another token exists; it does not consume it or verify that it is an integer.
  • nextInt() consumes one integer token. Spaces and line breaks separate tokens.
  • throws IOException lets file-opening failures propagate to the caller. It does not repair a missing file; if uncaught in this program, the failure stops execution.
  • close() releases the scanner’s resources when reading is complete.

Think about it: Point to the exact statement that moves the scanner forward. What happens if we remove it but leave the loop condition?

Check your reasoning

input.nextInt() consumes input. Without any consuming read inside the loop, hasNext() keeps reporting the same available token, so a nonempty file can cause an infinite loop.

Run the attendance report

Predict the output before clicking Run: Days: 4, Total: 80. Adding 30 should produce Days: 5, Total: 110.

The supplied sampleFile helper writes a real temporary file on the runner’s computer, then the program reads it with Scanner(File). This setup makes the demo independent of files on your laptop. File-writing setup is provided for testing; the skill to practice is reading the file. For a local file, replace sampleFile(...) with new File("attendance.txt") after creating that file yourself. A Scanner constructed from a String would scan the String’s contents, not open a file.

Code Runner Challenge

Predict days and total, then append 30 to the sample and rerun.

View IPYNB Source
// CODE_RUNNER: Predict days and total, then append 30 to the sample and rerun.
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class AttendanceLab {
// Supplied test setup: creates a real temporary text file for this run.
    public static File sampleFile(String text) throws IOException {
        File file = File.createTempFile("csa-attendance-", ".txt");
        file.deleteOnExit();
        PrintWriter writer = new PrintWriter(file);
        writer.print(text);
        writer.close();
        return file;
    }
    public static void main(String[] args) throws IOException {
        File file = sampleFile("18 24\n21 17\n");
        Scanner input = new Scanner(file);
        int days = 0;
        int total = 0;
        while (input.hasNext()) {
            int students = input.nextInt();
            total += students;
            days++;
        }
        input.close();
        System.out.println("Days: " + days);
        System.out.println("Total: " + total);
    }
}
AttendanceLab.main(null);

Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Partner activity: be the scanner

One partner points to the next unread token. The other updates the variables. Swap roles after two iterations.

Predict: Does the line break after 24 change the total?

Iteration Token consumed total after addition days after increment
1 18 … …
2 24 … …
3 21 … …
4 17 … …
Check your reasoning
Iteration Token total days
1 18 18 1
2 24 42 2
3 21 63 3
4 17 80 4

The output is Days: 4 followed by Total: 80. The newline separates tokens just like a space here. After the fourth read, hasNext() is false.

Change the input: An empty file produces Days: 0 and Total: 0. A file containing 18 absent 21 fails at nextInt() when the next token is absent; hasNext() alone does not guarantee a numeric token.

Your response

  • My predicted total:
  • The statement that consumes data:
  • What changes if I add 30 on a new line:
  • My explanation of the empty-file result:

Choose the reading method

Each row below is an independent reading situation; assume the scanner is at the start of the shown input.

Input What you want Method Result type
24 One integer nextInt() int
3.5 One decimal value nextDouble() double
true One Boolean value nextBoolean() boolean
Robotics Club The first word next() String
Robotics Club The whole line nextLine() String
Any remaining token Whether something is available hasNext() boolean

Quick vote: A club name contains spaces. Should we read the name with next() or nextLine()? Explain the information we lose with the other choice.

For this lesson, use separate scanners/examples for token reading and line reading. Mixing nextLine() with token-reading methods on one input source is outside the specified AP exam scope for this topic.

Turn one line into fields

Suppose clubs.txt has exactly these two nonblank lines, with one comma per line and no embedded commas:

Robotics,Room 12
Art,Room 8

Inside a method declared with throws IOException, and with the earlier imports:

Scanner clubs = new Scanner(new File("clubs.txt"));
while (clubs.hasNext()) {
    String line = clubs.nextLine();
    String[] fields = line.split(",");
    System.out.println(fields[0] + " meets in " + fields[1]);
}
clubs.close();

split(",") creates a String array. Array indexing still starts at zero. This example assumes every line follows the two-field format; arbitrary CSV files can be more complicated.

Predict: What is fields.length for the first record? What is printed?

Check your reasoning

fields.length is 2. The two output lines are:

Robotics meets in Room 12
Art meets in Room 8

The name example needs nextLine(): next() would return only Robotics. The club loop uses only line reads; hasNext() checks availability without consuming input. Its stated nonblank, consistently formatted input makes this pattern suitable here.

Code Runner Challenge

Predict both lines, then change a club name to include spaces.

View IPYNB Source
// CODE_RUNNER: Predict both lines, then change a club name to include spaces.
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class ClubFileLab {
// Supplied test setup: creates a real temporary text file for this run.
    public static File sampleFile(String text) throws IOException {
        File file = File.createTempFile("csa-attendance-", ".txt");
        file.deleteOnExit();
        PrintWriter writer = new PrintWriter(file);
        writer.print(text);
        writer.close();
        return file;
    }
    public static void main(String[] args) throws IOException {
        File file = sampleFile("Robotics Club,Room 12\nArt Club,Room 8\n");
        Scanner input = new Scanner(file);
        while (input.hasNext()) {
            String[] fields = input.nextLine().split(",");
            System.out.println(fields[0] + " meets in " + fields[1]);
        }
        input.close();
    }
}
ClubFileLab.main(null);

Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Debug before you code

A classmate writes this loop for a file of integers:

while (input.hasNext()) {
    input.nextInt();
    total += input.nextInt();
}

Talk through 18 24 21 17. Which values contribute to total? What if a fifth value is appended?

Check your reasoning

The first read in each iteration discards a number. Only 24 and 17 are added, for 41. With an odd number of tokens, the final iteration consumes the last token with the first call and then tries to read past the end with the second call. Fix this by reading once into a variable and using that variable.

Popcorn hack: count busy days

Write a method countBusyDays(String filename) throws IOException that returns how many integers in a file are at least 20.

Contract: The file exists, contains only valid integer tokens, and may be empty. Read every token once. Close the scanner. Do not assume a fixed number of days.

Use the imports from the complete program and place this method inside a class.

public static int countBusyDays(String filename) throws IOException {
    // Open a scanner.
    // Count values >= 20.
    // Close the scanner and return the count.
}
File contents Expected return
18 24 21 17 2
20 1
19 0 0
Empty file 0
Reveal a solution after writing yours
public static int countBusyDays(String filename) throws IOException {
    Scanner input = new Scanner(new File(filename));
    int busyDays = 0;
    while (input.hasNext()) {
        int attendance = input.nextInt();
        if (attendance >= 20) {
            busyDays++;
        }
    }
    input.close();
    return busyDays;
}

Self-check: Did you open the provided filename, consume one value per iteration, include exactly 20, close the scanner, and return zero for an empty file?

Code Runner Challenge

Complete countBusyDays, then check the boundary value 20 and an empty file.

View IPYNB Source
// CODE_RUNNER: Complete countBusyDays, then check the boundary value 20 and an empty file.
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class BusyDaysPractice {
// Supplied test setup: creates a real temporary text file for this run.
    public static File sampleFile(String text) throws IOException {
        File file = File.createTempFile("csa-attendance-", ".txt");
        file.deleteOnExit();
        PrintWriter writer = new PrintWriter(file);
        writer.print(text);
        writer.close();
        return file;
    }
    public static int countBusyDays(String filename) throws IOException {
        // TODO: Open a Scanner, read each integer once, count values >= 20,
        // close the Scanner, and return the count.
        return -1;
    }
    public static void main(String[] args) throws IOException {
        String[] data = {"18 24 21 17", "20", "19 0", ""};
        int[] expected = {2, 1, 0, 0};
        for (int i = 0; i < data.length; i++) {
            int actual = countBusyDays(sampleFile(data[i]).getPath());
            System.out.println((actual == expected[i] ? "PASS" : "FAIL")
                + " case " + i + ": expected " + expected[i] + ", actual " + actual);
        }
    }
}
BusyDaysPractice.main(null);

Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Your solution

// Write countBusyDays here.

My trace for the boundary value 20:

One test I would add and its expected result:

Exit ticket

Answer individually before opening the key.

  1. What is the difference between hasNext() and nextInt()?
  2. Why might new Scanner(new File("attendance.txt")) fail even when the code compiles?
  3. Given String record = "Meryl,Blue";, what does record.split(",")[1] produce?
Exit-ticket key
  1. hasNext() checks availability without advancing. nextInt() consumes a token as an integer and can fail if the token is invalid or unavailable.
  2. The path may not locate a readable file in the working directory.
  3. The String "Blue".

Homework: plan seats from the saved report

The club wants the total attendance on busy days, not just the number of busy days. Implement totalAtLeast(filename, threshold): add only values greater than or equal to the threshold. Use File and Scanner, consume each integer once, and close the scanner. Assume the file contains valid nonnegative integers and the sum fits in an int.

Before coding, trace 18 24 21 17 with threshold 20: the selected numbers are 24 and 21, so the total is 45. Explain why 2 would answer a different question. The starter compiles but intentionally prints FAIL until you implement the method. Do not change the expected values to make a test pass.

Code Runner Challenge

Write totalAtLeast and run all five checks; then add your own test.

View IPYNB Source
// CODE_RUNNER: Write totalAtLeast and run all five checks; then add your own test.
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class AttendanceHomework {
// Supplied test setup: creates a real temporary text file for this run.
    public static File sampleFile(String text) throws IOException {
        File file = File.createTempFile("csa-attendance-", ".txt");
        file.deleteOnExit();
        PrintWriter writer = new PrintWriter(file);
        writer.print(text);
        writer.close();
        return file;
    }
    public static int totalAtLeast(String filename, int threshold) throws IOException {
        // TODO: Return the SUM of attendance values >= threshold, not their count.
        // The file exists, has only valid nonnegative integers, and may be empty.
        return -1;
    }
    public static void main(String[] args) throws IOException {
        String[] data = {"18 24 21 17", "20", "19 0", "", "20\n20 21"};
        int[] thresholds = {20, 20, 20, 20, 20};
        int[] expected = {45, 20, 0, 0, 61};
        for (int i = 0; i < data.length; i++) {
            int actual = totalAtLeast(sampleFile(data[i]).getPath(), thresholds[i]);
            System.out.println((actual == expected[i] ? "PASS" : "FAIL")
                + " case " + i + ": expected " + expected[i] + ", actual " + actual);
        }
    }
}
AttendanceHomework.main(null);

Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

References and next steps

All Java lessons