How to count words in a text file, java 8-style

前端 未结 2 1740
日久生厌
日久生厌 2020-12-11 13:03

I\'m trying to perform an assignment that first counts the number of files in a directory and then give a word count within each file. I got the file count alright, but I\'m

2条回答
  •  时光说笑
    2020-12-11 13:49

    In my opinion, the simplest way to count the words in a file using Java 8 is this:

    Long wordsCount = Files.lines(Paths.get(file))
        .flatMap(str->Stream.of(str.split("[ ,.!?\r\n]")))
        .filter(s->s.length()>0).count();
    System.out.println(wordsCount);
    

    And to count all the files:

    Long filesCount = Files.walk(Paths.get(file)).count();
    System.out.println(filesCount);
    

提交回复
热议问题