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

  1. Read line by line
  2. Increment counter for each line
  3. Empty file has 0 lines

Related File I/O exercises

Practice all File I/O exercises · Run this idea in the Java compiler