How to read .txt file line by line in Java?

(Last Updated On: April 1, 2017)

How to read .txt file line by line in Java?

.txt file can be read line by line using bufferedreader. BufferedReader takes filereader as input and it takes .txt file as input.
readLine() method can be used to find whether any text is there or not in that line or last line is reached using br.readLine()!=null condition and line can be read and printed directly.

 

Reading .txt file line by line in Java Source code:


package in.javadomain;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class ReadLineByLine {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("c:\\sample.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

 

input text file:

.txt file has the below contents:

line 1
line 2
line 3
line 4
line 5 | extra text
line 6
line 7
line 8
line 9
line 10

 

Program Console Output:
line 1
line 2
line 3
line 4
line 5 | extra text
line 6
line 7
line 8
line 9
line 10

251 total views, 2 views today

Leave a Reply

Your email address will not be published. Required fields are marked *