在文本文件中查找特定单词并对其进行计数

6 java string search file count

有人可以帮我代码吗?如何在文本文件中搜索任何单词并计算重复的数量?

例如test.txt:

hi
hola
hey
hi
bye
hoola
hi
Run Code Online (Sandbox Code Playgroud)

如果我想知道在test.txt中重复多少次"Hi"程序必须说"3次重复"

我希望你理解我想要的东西,谢谢你的答案.

Udo*_*ski 11

public int countWord(String word, File file) {
int count = 0;
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
    String nextToken = scanner.next();
    if (nextToken.equalsIgnoreCase(word))
    count++;
}
return count;
}
Run Code Online (Sandbox Code Playgroud)