mightyplate
mightyplate

Reputation: 1

Counting amount of lines in txt file java file io

while (inputStream.hasNextLine()){
    System.out.println(count);
    count = count + 1 ;
}

For example my text file has 1,000 lines, Each line having information on it. It seems to be counting all of the digits and not every line.

Upvotes: 0

Views: 49

Answers (2)

Reimeus
Reimeus

Reputation: 159754

Assuming inputStream is a Scanner you need to consume the data from the InputStream

while (inputStream.hasNextLine()) {
   inputStream.nextLine(); <-- add this
   ...

Upvotes: 3

assylias
assylias

Reputation: 328598

Your loop never ends because you don't consume the stream. An alternative using Java 8:

try (Stream<String> s = Files.lines(Paths.get(file), UTF_8)) {
  count = s.count();
}

Upvotes: 1

Related Questions