Previously I have posted about reading text file using FileInputStream and BufferedReader. This post shows how to read text files in java using the Scanner class.
This is a sample text file
and this is the java code to read text files using the 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
Cheers 🙂 Happy Learning
No comments :
Post a Comment