AP Computer Science A · Unit 4 lecture · Part 5 of 14 · 9 min

4.6 Using text filesReading data from a text file

Mr. Thompkins
Real data sets don't get typed into your program by hand. They sit in files, sometimes thousands of lines long. Let's read one.

A text file is just lines of characters. To read one, you need two classes. File, from java.io, names the file. Scanner, from java.util, reads it piece by piece. You build the Scanner with the File: new Scanner(new File("trips.txt")). Opening a file can fail, for example if it doesn't exist, so any method that does it must say so in its header with throws IOException.

trips.txt, line by line
Ana,12
Ben,7
Cy,15
Dee,4
The text file the program reads: one rider and one distance in kilometers per line.
1import java.io.File;12import java.io.IOException;13import java.util.Scanner;145public class TripReport6{7    public static void main(String[] args) throws IOException28    {9        Scanner in = new Scanner(new File("trips.txt"));310        int total = 0;11        int count = 0;12        while (in.hasNext())413        {14            String line = in.nextLine();515            String[] parts = line.split(",");516            int km = Integer.parseInt(parts[1]);517            total += km;18            count++;19            if (km > 10)20            {21                System.out.println(parts[0] + " rode " + km);22            }23        }24        in.close();625        System.out.println((double) total / count);26    }27}
  1. line 1-3 File and IOException live in java.io; Scanner in java.util
  2. line 7 Opening a file can fail, so the header says throws IOException
  3. line 9 A Scanner that reads from the file instead of the keyboard
  4. line 12 Keep going while there is more to read
  5. line 14-16 One line, split at the comma, text to int
  6. line 24 Close the file when you are done
output › Ana rode 12 Cy rode 15 9.5
Read every line, split it, convert the number, and keep a running total.
?Wait, what does split do?
split is a String method on the Quick Reference. line.split(",") cuts the String at every comma and returns the pieces as a String array. "Ana,12".split(",") is {"Ana", "12"}, so parts[0] is the name and parts[1] is the distance, still as text.
?Wait, what does Integer.parseInt do?
It turns a String of digits into an int: Integer.parseInt("12") is 12. You need it because everything read from a file as a line or token is a String. If the String isn't a number, like "twelve", it throws a NumberFormatException.

The loop shape is always the same: while (in.hasNext()) asks "is there anything left to read?", and the body reads the next piece. When the file runs out, hasNext() returns false and the loop ends. Then close the Scanner to release the file.

CallWhat it readsReturns
new Scanner(new File("x.txt"))opens x.txt for readinga Scanner
in.nextInt()the next token, as a numberint
in.nextDouble()the next token, as a numberdouble
in.nextBoolean()the next token, true or falseboolean
in.next()the next token, up to a space or line endString
in.nextLine()the rest of the current lineString
in.hasNext()nothing; it only looks aheadtrue if more input remains
in.close()nothing; it releases the filevoid
The Scanner methods on the Java Quick Reference.

Scanner reads in two styles. nextInt(), nextDouble(), nextBoolean() and next() read one token: a piece of text up to the next space or line end, no matter how the lines are arranged. nextLine() reads everything left on the current line. One warning: after nextInt(), the rest of that line, often just the line break, is still waiting, so a nextLine() right after it returns that leftover, usually an empty String. The simplest habit is to read whole lines and split them, as TripReport does.

1public static void main(String[] args)2{3    Scanner in = new Scanner(new File("trips.txt"));14}
  1. line 3 error: unreported exception FileNotFoundException; must be caught or declared to be thrown
output › compile error: add throws IOException to the header
Leave off throws IOException and the program won't compile.
Pause and think
TripReport's total is 38 kilometers over 4 rides. Why does it print 9.5 and not 9?
I thought about it. Show me
Because of the (double) cast: (double) total / count is 38.0 / 4, which keeps the decimal part. Without the cast, 38 / 4 is integer division and gives 9.
Read tokens

The file nums.txt holds two lines: "4 7 2" and "9". What does this code print?

Scanner in = new Scanner(new File("nums.txt"));
int count = 0;
while (in.hasNext())
{
    int v = in.nextInt();
    if (v % 2 == 0)
    {
        count++;
    }
}
in.close();
System.out.println(count);
  1. nextInt reads tokens, so the line breaks don't matter. The tokens come out in order: 4, 7, 2, 9.
    Why?
    Tokens are separated by any whitespace: spaces or line breaks.
  2. Check each one: 4 is even (count 1), 7 is odd, 2 is even (count 2), 9 is odd.
  3. After 9, hasNext() is false, the loop ends, and the code prints 2.

Answer: 2

Stuck? Get a hint
  1. Does nextInt care which line a number is on?
  2. List all four numbers in reading order.
  3. v % 2 == 0 is true for even numbers.
Check yourself
Using the file trips.txt shown above, what does the first call to in.next() return?
  1. A"Ana,12"
  2. B"Ana"
  3. C"12"
  4. D"Ana,12 Ben,7"
Show the answer

A. next() reads one token, up to a space or a line end. The first line has no spaces, so the whole line "Ana,12" is one token. The second choice is the trap: next() doesn't stop at commas. That's why the program splits the line itself.

  • new Scanner(new File("name.txt")) opens a file. Import java.io.File, java.io.IOException and java.util.Scanner.
  • A method that opens a file needs throws IOException in its header.
  • while (in.hasNext()) reads until the input runs out. Close the Scanner at the end.
  • next, nextInt, nextDouble and nextBoolean read one token; nextLine reads the rest of the line.
  • split(",") breaks a line into a String array; Integer.parseInt and Double.parseDouble turn text into numbers.