Reading Files with Scanner (Part 1)

 Pre-requisites : Scanners ,While Loop

File Reading using Scanner

In Java a text file can be read by many ways , in this tutorial we will learn to read a text file by using scanner class.


Why read text files in Java ?

  • Text Files are very easy to write and are used extensively , eg:- Notepad files.
  • It can be easily edited and is hassle free too..
  • It can store very large amount of information.
To read files in Java there is a pre-built class File class which has all the necessary methods in it.


Let us see a Program where we read a text file :
  • Step 1 : Create a notepad text file in your desired directory / location . Here I am creating a text file named " example " on desktop.

  • Step 2 : Now you have created a file. Let us go to the Java compiler , now to specify the location of file so the Java compiler could read it we have to store the file location in a String.
 String fileLoc = "C:\\Users\\Desktop\\example.txt";  
Here I have used " \\ " because java compiler interprets this " \ " as a special character sequence and gives error as it is not able to read that character. So one can use " \\ " in place of " \ " or one can also use backward slash " / " in place of single forward slash.


  • Step 3 : As now we have the file location , we have to specify Java compiler that this is a file location and not a regular string. For this first we must declare a File class and then specify the location. 
 File file = new File(fileLoc);  
Here I have created an Object named file from File Class. And in the form of parameter we must pass the string which we have initialized with file location OR one can also directly pass the location as shown below.
 File file = new File("C:\\Users\\Desktop\\example.txt");  
Here we have to press Ctrl + Shift + O to import File package.


  • Step 4 : Now we have to declare a Scanner to read text files and supply the File Object ( here file ) as a argument to it. This will make compiler understand that user needs to read a file using scanner which has a location initialized before.
 Scanner scan = new Scanner(file);  
Here again we have to press Ctrl + Shift + O to import Scanner package. But you will notice that this line will have an error like symbol.


Here we have to click that error-like symbol , it would open a pop-up shown below.
 

Now click on Add throws declaration , this would add a throws FileNotFoundException statement to your main method.

These types of errors are called as Exceptions , they are to be handled and this functionality is called as Exception Handling. We will learn about this in detail in the next tutorials.

In above code , FileNotFoundException is just a warning from the Java compiler that it will display this message when file of your entered location is not found. You can also try this by altering your defined location and compiler will display the FileNotFoundException error.


  • Step 5 : Now we normally have to use a loop to read all the lines from the file. It would be written as : 
 import java.io.File;  
 import java.io.FileNotFoundException;  
 import java.util.Scanner;  
   
 public class MyClass {  
      public static void main(String[] args) throws FileNotFoundException {  
           File file = new File("C:\\Users\\Desktop\\example.txt");  
           Scanner scan = new Scanner(file);  
             
           // using while loop to read lines from file  
           while (scan.hasNext()) {  
                String line = scan.nextLine();  
                System.out.println(line);  
           }  
           scan.close();  
      }  
 }  
Output:-
 Hello I am a Text File.  
 This is my 2nd line.  
 This is my 3rd line.  
 Thank You.  



If we alter the destination of file , we get the following error.
 File file = new File("C:\\Users\\Desktop\\examplee.txt");  
Output:-
 Exception in thread "main" java.io.FileNotFoundException: C:\Users\Desktop\examplee.txt (The system cannot find the path specified)    

 Other ways to read text files will be explained in following tutorials.



< Previous Next >