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:
[java]
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();
}
}
}
[/java]
input text file:
.txt file has the below contents:
[plain]
line 1
line 2
line 3
line 4
line 5 | extra text
line 6
line 7
line 8
line 9
line 10
[/plain]
Program Console Output:
[plain]
line 1
line 2
line 3
line 4
line 5 | extra text
line 6
line 7
line 8
line 9
line 10
[/plain]