A simple Java program demonstrating how to read a file using java.util.Scanner class.
1. Create a text file say demo as customer.txt below -
a. customer.txt
2. Create a Java class to read customer.txt file -
Output of the program at the console :
1. Create a text file say demo as customer.txt below -
a. customer.txt
-------Customer Details ------- First Name : Jonty Last Name : Magic Email : Jonty@Magicman -------------------------------
2. Create a Java class to read customer.txt file -
package com.hubberspot.example; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class ScannerExample { public static void main(String[] args) { try { // Creating a file with a name customer.txt // placed in the root folder of your Java // project in eclipse // Storing the name of file as a String String fileName = "customer.txt"; // Creating a File object by passing it a // String containing the name of file File file = new File(fileName); // Creating a Scanner object using a constructor // which takes the file object. There are various // constructors for Scanner class for different // purposes. We want to use Scanner class to read // data from a file on the system, So we are using // a constructor which is taking an File object Scanner scanner = new Scanner(file); // Scanner class has many methods for scanning file // line-by-line. We use hasNextLine method which returns // true if there is yet another line to be read. putting the // condition in the while loop we traverse file line by line // and as soon as new line is figured out, we capture it by // Scanner class's nextLine method and prints it on the console while(scanner.hasNextLine()) { String readLine = scanner.nextLine(); System.out.println(readLine); } } catch (FileNotFoundException e) { e.printStackTrace(); } } }
Output of the program at the console :