Question:
How to get the total number of lines of a file in Java?
Code:
import java.io.FileReader; import java.io.IOException; import java.io.LineNumberReader; public class CountLines { public static void main(String[] args) { try{ FileReader fr = new FileReader("./CountLines.java"); LineNumberReader lnr = new LineNumberReader(fr); int count = 0; while (lnr.readLine() != null){ count++; } System.out.println("Total number of lines : " + count); lnr.close(); } catch(IOException e) { System.out.println(e); } } }
Output:
$ java CountLines Total number of lines : 27 $ wc -l CountLines.java 27 CountLines.java