Site icon TestingDocs.com

Read a file in Java using Scanner class

Introduction

On this page, we will learn how to read a text file using a Scanner class in a Java program. Scanner class is used to read input from the user using the standard console input peripheral device like a keyboard.

https://www.testingdocs.com/questions/how-to-get-input-from-keyboard-using-scanner-class/

In this java program, we will use a Scanner class to read from a text file. The text file is a simple file containing integers on each line. The file name is scores.txt

Java Code

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

public class ReadTextFileUsingScannerDemo {

  public static void main(String[] args) {
    try
    {   Scanner sc = new Scanner( new File("scores.txt") );
    while( sc.hasNextInt() )
    {	System.out.println( sc.nextInt() );
    }
    }
    catch(IOException e)
    {	System.out.println( e.getMessage() );
    }

  }
}

 

Sample Output

90
95
80
85
73

Screenshot

Exit mobile version