BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
int lines = 0;
while (reader.readLine() != null) lines++;
reader.close();
Update: To answer the performance-question raised here, I made a measurement. First thing: 20.000 lines are too few, to get the program running for a noticeable time. I created a text-file with 5 million lines. This solution (started with java without parameters like -server or -XX-options) needed around 1Best Answereconds on my box. The same with wc -l
(UNIX command-line-tool to count lines), 1Best Answereconds. The solution reading every single character and looking for ‘\n’ needed 104 seconds, 9-10 times as much.