Menu
Topics Index
...
`

Instantiating a Scanner object by passing a File object as parameter - Java Example Program


Instantiating a Scanner object by passing a File object as parameter
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

class ScannerConstructorDemo1
{
    public static void main(String arg[])
    {
        // Read from a file rather than the keyboard
        Scanner sc = new Scanner(new File("FIFA14.txt"));    // LINE A
        
        // Check if sc has another token in the file
        while(sc.hasNext())
            System.out.println(sc.next());
        
        // Close the scanner
        sc.close();    
    }
}
OUTPUT

Germany
Argentina
Netherlands
Brazil
Colombia
France
Costa-Rica
Belgium

DESCRIPTION

Here, we have instantiated a Scanner object by passing a file (FIFA14.txt)(LINE A). (Assume that FIFA14.txt exists.) hasNext() returns true if the input file has another token. SOP statement prints out each token. Finally, close() closes the scanner.

© meritcampus 2019

All Rights Reserved.

Open In App