public class Util{
public static void main(String[] args) throws IOException {
//鍵盤錄入指定文件名
Scanner sc = new Scanner(System.in);
String fileName = sc.nextLine();
//調用方法,求結果
countWord(fileName);
}
public static void countWord(File filename) throws IOException {
Util util = new Util();
String[] str = util.readFile(filename);
Map<String,Integer> map = new HashMap<String,Integer>();
//遍歷數組(即整篇文章)
for(String word : str){
if(map.containsKey(word)){
//包含該單詞則加1
map.put(word, map.get(word)+1);
}else{
//第一次出現則爲1
map.put(word, 1);
}
}
util.printCount(map);
}
public String[] readFile(File filename) throws IOException {
Reader reader = new FileReader(filename);
//BufferedReader可以讀取行,讀取速度快
BufferedReader br = new BufferedReader(reader);
//用於將讀取的每一句拼接,去除邊緣截斷單詞
StringBuffer sbu = new StringBuffer();
String line = "";
while (null != (line = br.readLine())) {
//拼接行
sbu.append(line);
}
// System.out.println(sbu);
String s = sbu.toString();
//正則中的非英文字符分割
String[] str = s.split("\\W");
return str;
}
//打印方法
public void printCount(Map map) {
Set<String> set = map.keySet();
for (String key : set) {
String str = key + "——>" + map.get(key);
System.out.println(str);
}
}
}