В Java 9+ вы можете посчитать, сколько раз слово встречается в текстовом файле следующим образом:
static long countWord(String filename, String word) throws IOException {
Pattern p = Pattern.compile("\\b" + Pattern.quote(word) + "\\b", Pattern.CASE_INSENSITIVE);
return Files.lines(Paths.get(filename)).flatMap(s -> p.matcher(s).results()).count();
}
Тест
System.out.println(countWord("test.txt", "the"));
test.txt
The quick brown fox
jumps over the lazy dog
Выход
2
Java 8 версия:
static int countWord(String filename, String word) throws IOException {
Pattern p = Pattern.compile("\\b" + Pattern.quote(word) + "\\b", Pattern.CASE_INSENSITIVE);
return Files.lines(Paths.get(filename)).mapToInt(s -> {
int count = 0;
for (Matcher m = p.matcher(s); m.find(); )
count++;
return count;
}).sum();
}
Java 7 версия:
static int countWord(String filename, String word) throws IOException {
Pattern p = Pattern.compile("\\b" + Pattern.quote(word) + "\\b", Pattern.CASE_INSENSITIVE);
int count = 0;
try (BufferedReader in = Files.newBufferedReader(Paths.get(filename), StandardCharsets.UTF_8)) {
for (String line; (line = in.readLine()) != null; )
for (Matcher m = p.matcher(line); m.find(); )
count++;
}
return count;
}
ОБНОВЛЕНИЕ
Полный код для Java 7+ версии, без использования метода, и используя гораздо более медленный Scanner
, поскольку OP, похоже, испытывает проблемы с копированием / вставкой описанных выше методов в свой код.
import java.io.File;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) throws Exception {
int count = 0;
try (Scanner in = new Scanner(new File("test.txt"))) {
Pattern p = Pattern.compile("\\bthe\\b", Pattern.CASE_INSENSITIVE);
while (in.hasNextLine())
for (Matcher m = p.matcher(in.nextLine()); m.find(); )
count++;
}
System.out.println("The total number of 'the' is " + count);
}
}
Для сравнения, полная версия, использующая первый метод в этом ответе, будет иметь следующий вид:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) throws IOException {
System.out.println("The total number of 'the' is " + countWord("test.txt", "the"));
}
static long countWord(String filename, String word) throws IOException {
Pattern p = Pattern.compile("\\b" + Pattern.quote(word) + "\\b", Pattern.CASE_INSENSITIVE);
return Files.lines(Paths.get(filename)).flatMap(s -> p.matcher(s).results()).count();
}
}