Count Lines in File in Java: Explanation & Practice
Count the number of lines in a file
Problem summary
Read a file and count how many lines it contains.
Starter code
import java.io.*;
public class Main {
public static void main(String[] args) {
// Count lines in file
// Print: Line count: <count>
}
}Expected output and test cases
- 5 lines in file
Line count: 5
Hints
- Read line by line
- Increment counter for each line
- Empty file has 0 lines
Related File I/O exercises
Practice all File I/O exercises · Run this idea in the Java compiler