TOPIC 4.6 · STUDY

Using Text Files

A text file stays on disk after the program ends. Topic 4.6 opens it with Scanner and File, reads tokens in a hasNext loop, then closes the Scanner. A missing file fails when that Scanner is constructed.

4.6.A

Using text files

A file is stored on disk. When main returns, local variables go away, but the file is still there for a later run. An open Scanner is a connection to a file during one run. Closing that Scanner, or ending the program, does not erase the file.

This course opens a text file by wrapping a File in a Scanner. The usual line is Scanner in = new Scanner(new File("name.txt"));. You need three imports: java.io.File, java.io.IOException, and java.util.Scanner. The method that builds that Scanner declares throws IOException.

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

public class PierWeights {
    public static int total(String path) throws IOException {
        Scanner in = new Scanner(new File(path));
        int sum = 0;
        while (in.hasNext()) {
            sum += in.nextInt();
        }
        in.close();
        return sum;
    }
}

hasNext is true while another token remains. nextInt reads the next integer token and adds it to sum. When hasNext becomes false, the loop stops and close releases the file connection. If path names a file that is not found, the failure happens when new Scanner(new File(path)) runs, not later in the loop.

A disk file feeds a Scanner, which adds each integer into a running sum.

Disk file to Scanner to sum. The file remains after the Scanner closes and after the program ends.

Other token readers used with a file Scanner in this topic are nextDouble for decimal tokens, nextBoolean for true or false, next for the next word token, and nextLine for one full line. Use one reading style on that Scanner for the run. Call close when the program is finished with the file Scanner.

Scanner in = new Scanner(new File("dock.txt"));
double sum = 0.0;
while (in.hasNext()) {
    sum += in.nextDouble();
}
in.close();
System.out.print(sum);

If dock.txt holds 1.5 then 2.5 then 4.0, the printed sum is 8.0. The same hasNext loop pattern works; only the reader changes. Keyboard System.in is not the file pattern for this topic.

Key points

  • A file persists on disk after the program ends; it is not the same as an open Scanner.
  • Open a file with Scanner in = new Scanner(new File("name.txt"));.
  • Import java.io.File, java.io.IOException, and java.util.Scanner; declare throws IOException.
  • A missing file fails when the Scanner is constructed.
  • Loop with hasNext, read with nextInt (or nextDouble, nextBoolean, next, or nextLine), then call close.

Closing the program does not delete the file. Ending main or calling close releases the Scanner connection; the saved text remains on disk for the next run.

Practice this topic