ACSA Exam Prep
Unit 4 · Data Collections · Topic 4.6

Using Text Files

Skill 2.CSkill 3.CSkill 4.B

Big idea: A text file keeps data after the program ends. Wrap it in a Scanner, then read it token by token or line by line until hasNext() is false.

Learning objectives
  • Develop code to read data from a text file.

Opening a file

Create a File with the file's name and pass it to a Scanner. Because the file might not exist, the method must say what happens then; the simplest way is throws IOException in the header. File and IOException are in java.io; Scanner is in java.util.

import java.io.*;
import java.util.*;

public static void main(String[] args) throws IOException {
  Scanner sc = new Scanner(new File("scores.txt"));
  // ... read ...
  sc.close();
}

Reading tokens

Suppose scores.txt holds a name and a score on each line. next() reads one word and nextInt() reads one integer, skipping spaces and line breaks.

scores.txt
Ava 91
Ben 78
Cy 85
Code
Scanner sc = new Scanner(new File("scores.txt"));
int total = 0;
while (sc.hasNext()) {
  String name = sc.next();
  int score = sc.nextInt();
  total += score;
  System.out.println(name + ": " + score);
}
sc.close();
System.out.println("total " + total);
Output
Ava: 91
Ben: 78
Cy: 85
total 254

Reading lines and splitting

For comma-separated data, read whole lines with nextLine() and break each into fields with split(","). Convert number fields with Integer.parseInt.

cities.txt
Austin,TX,979882
Boise,ID,237446
Dover,DE,39403
Code
Scanner sc = new Scanner(new File("cities.txt"));
String biggest = "";
int most = 0;
while (sc.hasNext()) {
  String[] f = sc.nextLine().split(",");
  int pop = Integer.parseInt(f[2]);
  if (pop > most) {
    most = pop;
    biggest = f[0];
  }
}
sc.close();
System.out.println(biggest);
Output
Austin

Scanner methods (on the Quick Reference)

MethodDoes
nextInt(), nextDouble(), nextBoolean()Read the next token as that type; throws InputMismatchException if it isn't one
next()Read the next token (word) as a String
nextLine()Read the rest of the current line
hasNext()Is there another token to read?
close()Close the scanner
Key points
  • A file stores data that persists after the program ends.
  • new Scanner(new File("data.txt")) connects to a file.
  • Handle the possible missing file with throws IOException in the header.
  • File and IOException are in java.io and need an import.
  • Loop with while (sc.hasNext()), and close the scanner when done.
  • split(del) breaks a line into a String[].
Watch out
  • Mixing nextLine with nextInt on the same source is excluded from the exam, so pick one style per file.
Quick check
A file has the numbers 4 9 2 on one line. What does a loop of sum += sc.nextInt() while sc.hasNext() produce?
Show answer
15.
Not on the exam
  • Keyboard input.
  • Code that mixes nextLine with other Scanner methods on one source.
  • Special regular-expression features in split (like \. or \*).