ADVERTISEMENT
ADVERTISEMENT

Java program to read a file line by line

In this java program, we are going to learn how to read a file line by line and print the line on the output screen? Here, we are reading content of a file line by line and printing.
Submitted by IncludeHelp, on November 19, 2017

Given a file and we have to read its content line by line using java program.

For this program, I am using a file named "B.txt" which is located at "E:\" drive, hence the path of the file is "E:\B.txt", and the content of the file is:

    This is line 1
    This is line 2
    This is line 3
    This is line 4

Program to read file line by line in java

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;

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

    // enter file name.
    System.out.print("Enter the file name:");
    String sfilename = Sc.next();
    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) {
      System.out.println(e);
    }
  }

Output

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

Java File Handling Programs »


ADVERTISEMENT




ADVERTISEMENT



Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.