Full explanation, traces and examples: Topic 4.6 study guide.
Recap
A file stores data that persists after the program ends. A program reads it by creating a File object from the file name and a Scanner from that File. The Scanner returns data forward only, a token or a line at a time.
Scanner in = new Scanner(new File(fileName));
while (in.hasNext())
{
// read with in.next(), in.nextInt(), in.nextDouble(), in.nextBoolean() or in.nextLine()
}
in.close();
The method that contains this code needs throws IOException in its header. File and IOException come from java.io; Scanner comes from java.util. Both need import statements.
Key relationships
| Item | Meaning | Remember |
|---|---|---|
File(String str) |
opens the file named str for reading |
only creates the link; no reading yet |
Scanner(File f) |
Scanner that reads from f |
needs throws IOException |
hasNext() |
is there another token? | looks only; does not move the cursor |
next() |
next token as String |
stops at whitespace |
nextInt(), nextDouble(), nextBoolean() |
next token as that type | InputMismatchException if the token is the wrong kind |
nextLine() |
rest of the line | may return "" straight after another reading method |
close() |
finished with the file | call it after the loop |
split(String del) |
String[] of pieces around del |
trailing empty pieces are dropped |
Assumptions the standard loop makes
- The file exists at the stated path (otherwise the program terminates).
- Every token has the kind the method expects.
- Records are complete: a line has all of its fields before it is split.
- Mixing
nextLinewith other Scanner methods on one source is outside the exam scope.
Mistakes to avoid
- Leaving out
throws IOExceptionor an import. - Treating
nextInt()as reading a whole line. - Calling
nextInt()twice when you meant to reuse one value. - Using
>=instead of>when the first of several tied records must win. - Using
hasNext()as if it advanced the cursor. - Assuming
"a,b,,".split(",")has four elements. Trailing empty strings are removed, so it has two (checked by running it). - Forgetting that an empty file means the loop body never runs.
A mini-example to rehearse
A file rain.txt holds 12 0 7 / 3 25 / 0 8 1. The loop while (in.hasNext()) { total += in.nextInt(); } runs eight times (one per token, not one per line) and leaves total at 56. If one token were the word two, the third nextInt() would throw InputMismatchException and total would never be returned.
For records such as Bilal,88 read with nextLine(), the pattern is: String[] parts = in.nextLine().split(","); then parts[0] is the name and Integer.parseInt(parts[1]) is the score. Keep the best-so-far in two variables and use strict > so that the first of two tied records stays.
How this topic is usually tested
- Trace a loop over a file described in words or as a table, and give the final value of a variable.
- Spot the missing piece: a missing
throws IOException, a missingimport, noclose(), or a loop that reads two tokens per pass. - Predict an exception: wrong-kind token, no data left, or a missing file.
- Write a method that reads numbers or records and returns a total, a count, a maximum or an average.
When you write code, state the loop condition first (hasNext()), then decide whether each pass reads a token or a line, and only then write the body.
Quick self-check
- A file holds
4 9 2. A loop adds eachnextInt()tototalwhilehasNext(). What istotal? 15 - Which header is needed for a method that builds a
Scannerfrom aFile?throws IOException(or code that handles it). - What does
"Bilal,88".split(",")[1]return?"88", aString. - A file holds
5 8 two 3. What is thrown by anextInt()loop?InputMismatchExceptionwhen it reachestwo. - How many times does a
next()loop run for a file withthe cat satandon the maton two lines? 6, one per token.