Using Text Files
A text file keeps data outside the program, so values written there are still there after the program stops. This lesson reads a small file about food trucks with the
Scanner class, one token at a time.The file
Each morning a city office writes
trucks.txt, one line per food truck: its name, its number of orders yesterday, and whether it takes cards.Taco 31 true
Noodle 18 false
Crepe 25 true
The counts change every day. Since they live in the file and not in the code, the same program reads each day's numbers without being edited or recompiled.
Opening the file
A program connects to a file through two classes. A
File object takes the file's name as its constructor argument, and a Scanner made from that File does the reading.Scanner sc = new Scanner(new File("trucks.txt"));The file might not be there, or its name might be misspelled. A method that opens a file has to say what happens then, and one way is to add
throws IOException to its header. The clause lets the method compile. If the name can't be opened when the program runs, the program terminates at that statement.Tokens
A
Scanner reads a file as a sequence of tokens, the runs of characters between whitespace. Spaces, tabs, and line breaks all count as whitespace. So trucks.txt holds nine tokens, and the line breaks separate them the same way the spaces do.The method
next() returns the next token as a String. The methods nextInt(), nextDouble(), and nextBoolean() return it as an int, a double, or a boolean. If the token can't be read as that type, they throw an InputMismatchException. Had the Noodle line said eighteen, the call to nextInt() that reached it would have thrown one.Every one of these calls uses up the token it returns. Two calls to
nextInt() in a row read two different numbers, and nothing can read a token a second time.Reading to the end
The method
hasNext() returns true while at least one token is left, and it uses nothing up. That makes it the condition of a while loop that reads until the file runs out.public static int cardOrders() throws IOException
{
Scanner sc = new Scanner(new File("trucks.txt"));
int total = 0;
while (sc.hasNext())
{
String name = sc.next();
int orders = sc.nextInt();
boolean cards = sc.nextBoolean();
if (cards)
{
total += orders;
}
}
sc.close();
return total;
}
Each pass reads one truck's three tokens, so the loop makes three passes and returns 31 + 25, or 56. The body reads
name even though nothing uses it. That read is how the scanner gets past the name to the number behind it.The loop ends because every pass uses up tokens. A body that read nothing would leave
hasNext() true forever.