import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws Exception {
String filePath = "C:/test.txt";
Test test = new Test();
try(Scanner scan = new Scanner(System.in)){
System.out.println("Please input the source word.");
String source = scan.nextLine();
int times = test.appearedTimes(source, filePath, false);
System.out.println(times);
}
}
/**
*
* @param source The specific word you will input
* @param filePath The TXT file's full path
* @param ignoreCase Whether ignore the word's case
* @return
* @throws Exception
*/
public int appearedTimes(String source, String filePath, boolean ignoreCase) throws Exception {
int times = 0;
File file = new File(filePath);
if(!file.exists() || !file.isFile()){
throw new Exception("File not found or isn't existing!");
}
try(BufferedReader reader = new BufferedReader(new FileReader(file));){
String content = null;
while((content = reader.readLine()) != null){
times += timesPerLine(ignoreCase ? content.toLowerCase() : content, ignoreCase ? source.toLowerCase() : source);
}
}
return times;
}
private int timesPerLine(String line, String source){
int times = 0;
if(line.indexOf(source) < 0){
return 0;
}
if(line == null || line.length() == 0){
return 0;
}
times ++;
String restString = line.substring(line.indexOf(source) + source.length());
times += timesPerLine(restString, source);
return times;
}
}
很简单啊,这些词语都是空格或回车换行符或标点符号分开的啊,所以对他们进行分割啊
用map存入啊,因为map是key+value的形式
key就是这个词语本身,value就是个数
正则表达式+map+Scanner就可以了啊