In this post we will see how to read file using Scanner in Java.
Scanner is a part of the java.util package. We will use
Scanner.nextLine() to read the file
How to read file using Scanner in Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
package com.kscodes.sampleproject; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class ScannerExample { public static void main(String[] args) { try { File fileTobeRead = new File("C:\\kscodes\test.txt"); Scanner scanner = new Scanner(fileTobeRead); while (scanner.hasNextLine()) { String line = scanner.nextLine(); System.out.println(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } } } |