C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
ReadLine: This method returns null when no more lines exist in the file (at end-of-file). We call it repeatedly.
LineCount: This int is incremented on each valid line read—when readLine does not return null.
Important: Make sure to change the file name passed to FileReader to one that exists on your system.
Java program that counts lines in file
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Program {
public static void main(String[] args) throws IOException {
int lineCount = 0;
// Get BufferedReader.
BufferedReader reader =
new BufferedReader(new FileReader("C:\\programs\\example.txt"));
// Call readLine to count lines.
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
lineCount++;
}
reader.close();
// Display the line count.
System.out.println("Line count: " + lineCount);
}
}
Contents of example.txt:
HELLO
FROM
DOT NET PERLS
Output
Line count: 3