涉及IO流中的读取文本、Map中的遍历
代码如下:
@Test
public void testReader2() {
File file = new File("tt.txt");
int startTime = (int) System.currentTimeMillis();
BufferedReader br = null;
try {
FileReader fr = new FileReader(file);
br = new BufferedReader(fr);
HashMap<Character, Integer> objectObjectHashMap = new HashMap<>();
int ca ;
while ((ca = br.read()) != -1){
char c = (char) ca;
if(objectObjectHashMap.containsKey(c)){
Integer newValue = objectObjectHashMap.get(c)+1;
objectObjectHashMap.put(c, newValue);
}else {
objectObjectHashMap.put(c,1);
}
}
Set<Map.Entry<Character, Integer>> entries = objectObjectHashMap.entrySet();
Iterator<Map.Entry<Character, Integer>> iterator = entries.iterator();
System.out.println(iterator.hasNext());
while (iterator.hasNext()){
Map.Entry entry = iterator.next();
System.out.println(entry.getKey()+"有"+entry.getValue()+ "个");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(br != null)
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
int finalTime = (int) System.currentTimeMillis();
System.out.println();
System.out.println("time is "+(finalTime-startTime));//测时间的,与题目无关
}