Skip Top Navigation Bar

Reading from a Text File using File and Scanner

We can read input from a variety of sources. In this lesson, we will explore reading data from a text file. This is great for when you have a lot of data that needs to be entered and hand keying the data would be time-consuming or introduce errors. One excellent beginner use for reading from a text file, is if you want to repeatedly test your program with the same input values. Recording these values in a text file will allow you to test your code without having to re-enter the data through the console each time.

We will also explore other ways to read from a file, but in this lesson we will use File and Scanner, as that is required for the AP Computer Science A exam.

File Class

We can use the File class to represent a file.

Constructor

We can create a File object using a String that contains the file path. If the file is in the same project folder as your .java file, you can use the name of the file as input.

File dataFile = new File(filepath);

If the file pile has backslash characters (\), you will need to use two, since this is an escape character.

Scanner Class

You can use the Scanner class to read from a file.

Constructor

The Scanner constructor can be used to create a Scanner object with a File object as the parameter.

Wrong File Path

What is the file gets moved? Or you have typed the file name or path incorrectly? Java will throw and excpetion when you try to create a Scanner object with a file path that doesn't exist. These cases, you will need to deal with the exceptions. There are a couple of different ways to deal this.

The AP Computer Science A course recommends that you add throws IOException to the header of the method that is using the file. For example:

void main() throws IOException { 
    File dataFile = new File ("input.txt");
    Scanner input = new Scanner (dataFile);
}

Another way that you can handle dealing with exceptions is by using a try..catch statement.

File dataFile = new File("input.txt");
try(Scanner input = new Scanner(dataFile)) {
   //statements if the "input.txt" path exists
} catch (FileNotFoundException error) {
   //statements if the file isn't found
}

Scanner Methods

Your Turn

Try the following in a desktop or online IDE.

Consider a grades.txt has the following values for grades:

85
95
65
70
90
100

If you wanted to write a program to compute the average of these grades, you could store these grades in grades.txt and repeated run the program until the average yielded the correct result.

void main() {
    File dataFile = new File("grades.txt");
    int total = 0;
    int count = 0;
    try(Scanner input = new Scanner (dataFile)) {
        while (input.hasNext()) {
            total += input.nextInt();
            count++;
        }
    } catch (FileNotFoundException error) {
        IO.println("Wrong file name");
    }
    if (count > 0) {
        IO.println (total / count);
    }
}

Another Example

Try the following in a desktop or online IDE.

Consider an input file that contains the direction and number of degrees a robot should turn. The direction can be L for left and R for right. And the number of degrees is between 0 and 360.

Consider the moves.txt files has the following Robot moves to try:

L90
R180
L60
L45
R30
R120

In this case, we have a mix of letters and numbers. You can separate these into direction and degrees by using a combination of substring and Integer.parseInt().

A program to turn the robot might look like the following:

void main() {
    File dataFile = new File("moves.txt");
    int degreeFacing = 0;

    try(Scanner input = new Scanner (dataFile)) {
        while (input.hasNext()) {
            String value = input.next();
            String direction = value.substring(0, 1);
            int degrees = Integer.parseInt(value.substring(1));
            if (direction.equals("R")) {
                degreeFacing += degrees;
            } else {
                degreeFacing -= degrees;
            }
        }
    } catch (FileNotFoundException error) {
        IO.println("Wrong file name");
    }
    IO.println(degreeFacing);
}

Resources

Please check back from more resources.

Next Learn Tutorial