Java Program to Read a File

This article covers a program in Java that reads a file, entered by user at run-time of the program.

Read a File Line by Line in Java

The question is, write a Java program to read a file, line by line using Scanner. The program given below is its answer:

import java.util.Scanner;
import java.io.*;

public class fresherearth
{
   public static void main(String[] args)
   {
      String myfile, myline;
      Scanner scan = new Scanner(System.in);
      
      System.out.print("Enter File Name: ");
      myfile = scan.nextLine();
      
      try
      {
         FileReader fileReader = new FileReader(myfile);
         BufferedReader bufread = new BufferedReader(fileReader);
         
         // reading the file, line by line
         while((myline = bufread.readLine()) != null)
            System.out.println(myline);
         
         bufread.close();
      }
      catch(IOException e)
      {
         System.out.println("Exception: " +e);
      }
   }
}

The snapshot given below shows the sample run of above program, with user input fresherearth.txt as name of file to read

java program read a file

In the above program, if you change the following block of code:

while((myline = bufread.readLine()) != null)
   System.out.println(myline);

with the block of code given below:

int line_no = 1;
while((myline = bufread.readLine()) != null)
{
   System.out.println("Line No." +line_no+ ": \"" +myline+ "\"");
   line_no++;
}

then the output will be:

java program to read a file line by line

The while loop, can also be replaced with for. Here is the for loop version of the same block, created using while:

int line_no = 1;
for(myline=bufread.readLine(); myline!=null; myline=bufread.readLine())
{
   System.out.println("Line No." +line_no+ ": \"" +myline+ "\"");
   line_no++;
}

The file fresherearth.txt is already available inside the current directory. The directory in which the above Java application's source code is saved.

Same Program in Other Languages

Java Online Test


« Previous Program Next Program »