4.6 Using text filesReading data from a text file

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 |
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}
- line 1-3 File and IOException live in java.io; Scanner in java.util
- line 7 Opening a file can fail, so the header says throws IOException
- line 9 A Scanner that reads from the file instead of the keyboard
- line 12 Keep going while there is more to read
- line 14-16 One line, split at the comma, text to int
- line 24 Close the file when you are done
?Wait, what does split do?
?Wait, what does Integer.parseInt do?
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.
| Call | What it reads | Returns |
|---|---|---|
| new Scanner(new File("x.txt")) | opens x.txt for reading | a Scanner |
| in.nextInt() | the next token, as a number | int |
| in.nextDouble() | the next token, as a number | double |
| in.nextBoolean() | the next token, true or false | boolean |
| in.next() | the next token, up to a space or line end | String |
| in.nextLine() | the rest of the current line | String |
| in.hasNext() | nothing; it only looks ahead | true if more input remains |
| in.close() | nothing; it releases the file | void |
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}
- line 3 error: unreported exception FileNotFoundException; must be caught or declared to be thrown
I thought about it. Show me
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);- 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. - Check each one: 4 is even (count 1), 7 is odd, 2 is even (count 2), 9 is odd.
- After 9, hasNext() is false, the loop ends, and the code prints 2.
Answer: 2
Stuck? Get a hint
- Does nextInt care which line a number is on?
- List all four numbers in reading order.
- v % 2 == 0 is true for even numbers.
- A"Ana,12"
- B"Ana"
- C"12"
- 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.