Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the count of line in a file in an efficient way? [duplicate]

Tags:

java

file

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?

like image 580
firstthumb Avatar asked Aug 14 '09 13:08

firstthumb


People also ask

How do I count the number of lines in a file?

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.

How do I count the number of lines in a file without opening the file?

If you are in *Nix system, you can call the command wc -l that gives the number of lines in file.

How do I count the number of lines in a Java project?

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!


2 Answers

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.

like image 118
Mnementh Avatar answered Oct 14 '22 15:10

Mnementh


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.

like image 32
Augustin Avatar answered Oct 14 '22 15:10

Augustin