Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java scanner count lines in file

I have a question, I tried to create an app that counts all occurences of a symbol in a file... The scanner method "nextLine" stops at an empty line... Is there a way to keep it going until it reaches the real end of the file?

In short: can I get the REAL number of lines in a file?

Thankyou in advance!

like image 721
Justas S Avatar asked Mar 22 '23 08:03

Justas S


2 Answers

You can use a loop:

int count = 0;
while (scanner.hasNextLine()) {
    count++;
    scanner.nextLine();
}

count will contain number of lines.

like image 85
Eugen Halca Avatar answered Mar 27 '23 21:03

Eugen Halca


So I've been doing some research about this problem. I've been coming up against it recently while writing a line counting program in Java for the class I'm taking.

The reason the scanner class does this is because scanner.next() and scanner.nextLine() return tokens, which are separated by delimiters. By default the delimiter is whitespace. So what's happening is that when you call scanner.hasNext() or scanner.hasNextLine() is that it looks to see if there is a token after the next delimiter. When a file ends in a newline character, there is no token after that, so hasNext() and hasNextLine() return false.

As far as I can tell, to do what you want you'd need to count the number of delimiters, which is better handled in Martinus's answer. See also AFinkelstein's answer.

like image 30
wolf123450 Avatar answered Mar 27 '23 20:03

wolf123450