简体   繁体   中英

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.

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

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

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM