Java Scanner Class to Read File Example



In this post, we will see how to use the Scanner class to read a file line by line with an example.

The Java Scanner class breaks the input into tokens using a delimiter which is whitespace by default. It provides many methods to read and parse various primitive values.

How to read the file line by line with an example

The following Java program uses the nextLine() method to read a text file line by line, and add all lines to a list of Strings:
package net.javaguides.examples;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

/**
 * Scanner class file read example
 * @author Ramesh Fadatare
 *
 */
public class ScannerFileReadExample {
    public static void main(String[] args) throws FileNotFoundException {
        String fileName = "sample.txt";

        try (Scanner scanner = new Scanner(new File(fileName))) {

            while (scanner.hasNext()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }
        }
    }
}
Create a file named "sample.txt" and add a few lines to it and run the above program to read a text file line by line using Scanner class.

Comments