public static void main(String[] args) throws Exception{
String word = "你";
String path = "D:/file/file.txt";
int occurTime = occurTime(path, word);
System.out.println(occurTime);
}
//统计文件中某个单词的出现次数
public static int occurTime(String path,String word) throws Exception {
BufferedReader br = new BufferedReader(new FileReader(path));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null){
sb.append(line);
}
String text = sb.toString();
//如果以word开始或结束,在开始前面或结束后面拼上一个默认字符,否则统计不完整
boolean isWordStart = text.startsWith(word);
if (isWordStart){
if ("a".equals(word)){
text = "b".concat(word);
}else {
text = "a".concat(word);
}
}
boolean isWordEnd = text.endsWith(word);
if (isWordEnd){
if ("a".equals(word)){
text = text.concat("b");
}else {
text = text.concat("a");
}
}
String[] splitString = text.split(word);
int occurTime = splitString.length - 1;
// System.out.println("出现次数=" + occurTime);
return occurTime;
}