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
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
Cheers 🙂 Happy Learning