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.io.File;
import java.io.FileNotFoundException;

import java.util.Scanner;

public class ReadFileScn {
    public ReadFileScn() {
        super();
    }

    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())
            System.out.println(s.nextLine());
    }

}

 

Execute this java code

Output is

Read text file in java using Scanner

Cheers 🙂 Happy Learning

Related Posts

An Oracle ACE, Blogger, Reviewer, Technical Lead working on Oracle ADF

Leave a Reply

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