本帖最后由 山西_李帅 于 2013-4-24 23:07 编辑
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;
/*
* 统计Demo4.java笔记中每个字符出现的次数
* 把结果输出到GBK.txt中. 结果按照字符顺序排序
*/
public class Demo5 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("D:/cn/itcast/src/day0424_lianxi/Demo4.java")); //定义BufferedReader
br.readLine();
Map<Character, Integer> map = new TreeMap<Character,Integer>(); //定义一个TreeMap集合
int x;
while((x = br.read()) != -1){
char c = (char)x;
map.put(c, map.containsKey(c) ? map.get(c)+1 : 1); //判断Map集合中是否包含 指定键,如果包含将返回的值加1,不包含直接记录1
}
br.close(); //关闭流
BufferedWriter bw = new BufferedWriter(new FileWriter("GBK.txt")); //定义BufferedWriter
for (char c : map.keySet()) { //遍历TreeMap集合
bw.write(c + ":" + map.get(c));
bw.newLine();
}
bw.close();
}
}
|