Java Language Reading file input using Scanner

Download Java Language for free

Example

Scanner scanner = null;
try {
    scanner = new Scanner(new File("Names.txt"));
    while (scanner.hasNext()) {
        System.out.println(scanner.nextLine());
    }
} catch (Exception e) {
    System.err.println("Exception occurred!");
} finally {
    if (scanner != null)
        scanner.close();
}

Here a Scanner object is created by passing a File object containing the name of a text file as input. This text file will be opened by the File object and read in by the scanner object in the following lines. scanner.hasNext() will check to see if there is a next line of data in the text file. Combining that with a while loop will allow you to iterate through every line of data in the Names.txt file. To retrieve the data itself, we can use methods such as nextLine(),nextInt(),nextBoolean(), etc. In the example above, scanner.nextLine()is used. nextLine() refers to the following line in a text file, and combining it with a scanner object allows you to print the contents of the line. To close a scanner object, you would use .close().

Using try with resources (from Java 7 onwards), the above mentioned code can be written elegantly as below.

try (Scanner scanner = new Scanner(new File("Names.txt"))) {
    while (scanner.hasNext()) {
        System.out.println(scanner.nextLine());
    }
} catch (Exception e) {
    System.err.println("Exception occurred!");
}
Reading system input using Scanner