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
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
Program to read file line by line in java
Output