Java Program to Read a File Line by Line

You are currently viewing Java Program to Read a File Line by Line

Java program to read a file line by line

import java.util.Scanner;

public class ReadLineByLine {
  public static void main(String[] args) {
    // create object of scanner class.
    Scanner Sc = new Scanner(;

    // enter file name.
    System.out.print("Enter the file name:");
    String sfilename =;
    Scanner Sc1 = null;
    FileInputStream fis = null;
    try {
      FileInputStream FI = new FileInputStream(sfilename);
      Sc1 = new Scanner(FI);

      // this will read data till the end of data.
      while (Sc1.hasNext()) {
        String data = Sc1.nextLine();

        // print the data.
        System.out.print("The file data is : " + data);
    } catch (IOException e) {


Enter the file name: E:/B.txt
This is line 1
This is line 2
This is line 3
This is line 4


Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply