Read Text File in Java using Scanner Class

Sharing is Caring

Previously I have posted about reading text file using FileInputStream and BufferedReader. This post shows how to read text file in java using Scanner class.

This is a sample text file

Sample Text File - Scanner Class

and this is the java code to read text file using Scanner class

package client;


import java.util.Scanner;

public class ReadFileScn {
    public ReadFileScn() {

    public static void main(String[] args) {
        // Absolute path of file that you want to read
        File f = new File("D:/sampleFile.txt");
        Scanner s = null;
        try {
            s = new Scanner(f);
        } catch (FileNotFoundException e) {

        //Iterate over file content
        while (s.hasNextLine())



Execute this java code

Output is

Read text file in java using Scanner

Cheers 🙂 Happy Learning

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *