I have a big file. It includes approximately 3.000-20.000 lines. How can I get the total count of lines in the file using Java?
Using “wc -l” There are several ways to count lines in a file. But one of the easiest and widely used way is to use “wc -l”. The wc utility displays the number of lines, words, and bytes contained in each input file, or standard input (if no file is specified) to the standard output. 1.
If you are in *Nix system, you can call the command wc -l that gives the number of lines in file.
After installation: - Right click on your project - Choose codepro tools --> compute metrics - And you will get your answer in a Metrics tab as Number of Lines. This one is actually quite good!
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 11 seconds on my box. The same with wc -l
(UNIX command-line-tool to count lines), 11 seconds. The solution reading every single character and looking for '\n' needed 104 seconds, 9-10 times as much.
Files.lines
Java 8+ has a nice and short way using NIO using Files.lines
. Note that you have to close the stream using try-with-resources:
long lineCount; try (Stream<String> stream = Files.lines(path, StandardCharsets.UTF_8)) { lineCount = stream.count(); }
If you don't specify the character encoding, the default one used is UTF-8. You may specify an alternate encoding to match your particular data file as shown in the example above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With