Task 5 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

6.1 Scanner — reading from a file

Lesson

Reading a text file

To read from a text file, build a File from the file name, then a Scanner from that File, and read with the same has…/next… methods. Call close() when finished. Because opening a file can fail, the method header declares throws IOException (or throws FileNotFoundException). On the exam you do not catch the error — you just declare it and focus on reading the data.


Worked example

public static void printFile(String fileName) throws IOException {
    File f = new File(fileName);           // 1. File from the name
    Scanner in = new Scanner(f);           // 2. Scanner from the File
    while (in.hasNextLine()) {             // 3. read until no more lines
        System.out.println(in.nextLine());
    }
    in.close();                            // 4. close when done
}

Remember it as Create File, Scanner from File, then loop — and close at the end. (Imports such as java.io.File and java.util.Scanner are provided; you do not write them on the exam.)


When you do not know how many values a file holds, read in a loop and add each value to an ArrayList: while (in.hasNextInt()) list.add(in.nextInt());. The runnable example below reads from typed input instead of a file, but the reading loop is exactly the same as it would be for a Scanner opened on a file.


▶ Try it: run this, type some whole numbers separated by spaces, and it reports the largest — the same loop you would use over a file.



To read from a text file, you construct a Scanner from a...


Because opening a file can fail, the method header should include...


Order the four steps to read a text file with a Scanner.


When you do not know how many numbers a file has, a good way to store them as you read is...


True or false?


Type exactly what this program prints.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner("dog cat");
        System.out.println(in.next());
        System.out.println(in.next());
    }
}