public class test { public static void main(String[] args) throws Exception { InputStream file = new FileInputStream("F://a.txt"); InputStreamReader inputStreamReader = new InputStreamReader(file); int i = 0 , count = 1; /* 基本思路 從文檔中從頭開始,逐次讀取字符,讓讀取的字符與keySet(也就是map的鍵集合)里的值作對比: 如果有,則讓map的value值 "+1" 賦給count,將鍵和值存到map集合里; 如果沒有,則將map的value值設為 "1",同樣,將鍵和值存到map集合里。 最后遍歷 */ HashMap<Character, Integer> hashMap = new HashMap<Character, Integer>(); Set<Character> keySet = hashMap.keySet(); while ((i = inputStreamReader.read()) != -1) { if (keySet.contains((char)i)) { count = (int) hashMap.get((char)i)+1; hashMap.put((char)i,count); } else { hashMap.put((char)i, 1); } }
//遍歷輸出 for (Character character : keySet) { System.out.println("鍵(字符):"+character+" 值(出現次數):"+hashMap.get(character)); } } }