10.3 Reading Data from Text File

In Section 2.5, you learned how to use a Scanner object to input data from the standard input device (keyboard). Recall that the following statement creates the Scanner object console and initializes it to the standard input device:

Scanner console = new Scanner(System.in);

You can also use the Scanner class to read input from a file. Instead of passing System.in to the Scanner class constructor, you pass a reference to a FileReader object. Here is an example:

FileReader fr = new FileReader("oceans.txt"); 
Scanner inFile = new Scanner(fr); 

Following program display the first two lines on screen of file oceans.txt that we have created in previous section.

import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class FileReadDemo
{
    public static void main(String[] args) throws IOException
    {
        // Open the file.
        FileReader fr = new FileReader("oceans.txt");
        Scanner inFile = new Scanner(fr);
        
        String line;
        
        // Read the first line from the file.
        line = inFile.nextLine();
        // Display the line.
        System.out.println(line);

        // Read second line from the file.
        line = inFile.nextLine();
        // Display the line.
        System.out.println(line);

        // Close the file.
        inFile.close();
    }
}

Output :

Atlantic
Pacific

 

Detecting the End of a File

Scanner method hasNext is used to determine whether there’s more data to input from file. This method returns the boolean value true if there’s more data; otherwise, it returns false.

In the following program, the returned value of hasNext method is used as the value of the condition in the while statement as end-of-file indicator.

import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class FileReadDemo
{
    public static void main(String[] args) throws IOException
    {
        // Open the file.
        FileReader fr = new FileReader("ocean.txt");
        Scanner inFile = new Scanner(fr);

        // Read lines from the file till end of file
        while (inFile.hasNext())
        {
            // Read the next line.
            String line = inFile.nextLine();
            // Display the line.
            System.out.println(line);
        }

        // Close the file.
        inFile.close();
    }
}

Output :

Atlantic
Pacific
Indian
Arctic
Southern