Unit 4 · 25 min

4.6 Using Text Files

Reading a file is a traversal: while there is a next item, read it and process it.

Summary, objectives and course and exam description (CED) codes

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.

By the end of this session you can

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

4.6.A4.6.A.14.6.A.24.6.A.34.6.A.44.6.A.54.6.A.64.6.A.74.6.A.84.6.A.94.6.A.10

Reviewed against the CED on

Know this already? Jump to the checkpoint.

1LearnThe notes, the traps and how to remember them

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 ":".

Lock it in: memory hooks

  • Opening a fileName it, scan it, read it, close it: new File, new Scanner, next..., close.
  • Reading loopAsk before you take: hasNext() first, then next().
  • Importsio for the file, util for the scanner.

Common misconceptions

  • "new File("data.txt") reads the data."

    Not quite. A File object only names the file to open. You pass it to the Scanner constructor, and the Scanner methods do the reading.

  • "If the file is missing, the program just reads nothing."

    Not quite. If the file cannot be opened, an exception is thrown and, with throws IOException in the header, the program terminates.

  • "next() returns the next line."

    Not quite. next() returns the next token, a piece of text up to the next whitespace. nextLine() returns the rest of the line as one String.

  • "File and Scanner are always available, like String."

    Not quite. 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.

Exam traps

  • Without throws IOException (or another way to handle it), the code does not compile.
  • nextInt on a token like abc throws an InputMismatchException at run time.
  • next() stops at whitespace, so "New York" is read as two tokens.
  • Calling a next method when hasNext() is false throws a NoSuchElementException.

2PracticeRecall it, then check yourself

In 30 seconds

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

Cover this list, say the points out loud, then take the checkpoint without scrolling back up.

Checkpoint · 5 questions

Checkpoint: Using Text Files

Pick an answer to mark it. Every answer is explained, and you can try any question again. Your saved score counts first tries only, and stays in this browser.

  1. 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? 4.6.A.4, 4.6.A.5
    public static int readFirst(String name)
    {
        Scanner sc = new Scanner(new File(name));
        int first = sc.nextInt();
        sc.close();
        return first;
    }
    Show answer

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

  2. nums.txt
    LineContents
    14 7
    22 9
    2 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? 4.6.A.6, 4.6.A.9
    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);
    Show answer

    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.

  3. mix.txt
    LineContents
    15 2.5 7
    3 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? 4.6.A.6
    Scanner in = new Scanner(new File("mix.txt"));
    int a = in.nextInt();
    int b = in.nextInt();
    System.out.println(a + b);
    in.close();
    Show answer

    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.

  4. 4 Consider the following code segment. What is printed as a result of executing the code segment? 4.6.A.8
    String rec = "Oslo:12:true";
    String[] p = rec.split(":");
    System.out.println(p.length + p[1]);
    Show answer

    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.

  5. city.txt
    LineContents
    1New York 8
    5 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? 4.6.A.1, 4.6.A.6, 4.6.A.10
    Scanner in = new Scanner(new File("city.txt"));
    String a = in.next();
    String b = in.next();
    in.close();
    System.out.println(b);
    Show answer

    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.

3PrevailLock it in for exam day

By the numbers

Name each list from memory, then reveal it to check. Each list shows how many items to recall.

  • Scanner constructor and methods in the Java Quick Reference eight members CED 4.6.A.6
    1. ScannerFile f
    2. int nextInt()
    3. double nextDouble()
    4. boolean nextBoolean()
    5. String nextLine()
    6. String next()
    7. boolean hasNext()
    8. void close()
  • Classes used to read a text file, and their packages three classes CED 4.6.A.2, 4.6.A.5
    1. Filejava.io
    2. IOExceptionjava.io
    3. Scannerjava.util
  • Outside the scope of the AP® exam for this topic three exclusions CED 4.6.A.6, 4.6.A.7, 4.6.A.8
    1. accepting input from the keyboard
    2. code that uses nextLine together with other Scanner methods on the same input source
    3. the special properties of regular expressions in split

Key terms: flip the cards

Read the term, say the definition out loud, then flip to check. Struggling a little to remember is what makes it stick.

  • Text filetap to flip

    Storage for data, as readable text, that persists when the program is not running and can be read while the program runs.

    Example and CED codes
  • File (class)tap to flip

    The java.io class whose constructor File(String str) connects a program to the file with that pathname so a Scanner can read it.

    Example and CED codes
  • Scanner (file input)tap to flip

    The java.util class that reads data from a file: Scanner(File f) with nextInt, nextDouble, nextBoolean, next, nextLine, hasNext and close.

    Example and CED codes
  • IOExceptiontap to flip

    The java.io exception class for input and output problems; adding throws IOException to a method header handles a file that cannot be opened.

    Example and CED codes
  • while looptap to flip

    An iterative statement that evaluates its Boolean expression before each iteration, including the first, and repeats its body while the expression is true.

    Example and CED codes
  • Stringtap to flip

    A class whose objects hold a sequence of characters. String is a reference type in java.lang, and String objects are immutable.

    Example and CED codes
  • Arraytap to flip

    An object that stores a fixed number of values of the same type, either primitive values or object references, reached by an index.

    Example and CED codes

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.

Was this page helpful?

No names are ever shown, and every public comment is checked by us first. Please do not include personal details. To get a reply, email [email protected].

↑ Top

Enlarged view of the selected figure