本帖最后由 jiangweibin2573 于 2014-8-10 18:13 编辑
- import java.io.*;
- import java.util.*;
- public class Test8 {
- public static void main(String[] args) {
-
- File fileName = new File("fileName.txt");//封装需要统计的文件
- File toFileName = new File("toFileName.txt");//统计结果存放位置
-
- countFunc(fileName,toFileName);//开始统计
- }
-
- /*思路:
- * (1)从文件中读取字符
- * (2)将字符存入TreeMap中,进行默认排序(字母和次数对应关系)
- * (3)将map中元素写到文件中
- */
-
- public static void countFunc(File fileName,File toFileName){
- BufferedReader br = null;
- BufferedWriter bw = null; //创建带缓冲的字符输入输出流
- try {
- br = new BufferedReader(new FileReader(fileName));//读取流与文件关联
- TreeMap<Character, Integer> tm = new TreeMap<Character, Integer>();//创建TreeMap集合,用来存统计
- String line = null;
- /*
- * 输入流每读取一行,就将改行转换为字符字符数组,并遍历数组,将其存入map中
- * 当map中以包含当前字母则将其值+1再存入,否则将值设为1存入
- */
- while((line=br.readLine())!=null){
- char[] ch = line.toCharArray();
- for(int i=0;i<ch.length;i++){
- if(tm.containsKey(ch[i]))//判断是否包含该键
- tm.put(ch[i], tm.get(ch[i])+1);
- else
- tm.put(ch[i], 1);
- }
- }
- /*
- *上面已完成全部字符存入map,接下来,遍历map集合,将其写入文件中
- */
- bw = new BufferedWriter(new FileWriter(toFileName));//将文件与输出流关联
-
- Set<Map.Entry<Character,Integer>> entrySet = tm.entrySet();//得到TreeMap的set集合
- Iterator<Map.Entry<Character, Integer>> it = entrySet.iterator();//迭代器
- while(it.hasNext()){
- Map.Entry<Character, Integer> me = it.next();
- Character key = me.getKey();
- Integer value = me.getValue(); //得到键和值
-
- bw.write(key+": "+value+" 次");//按指定格式写入缓冲区
- bw.newLine();
- bw.flush(); //换行并刷新
- }
- System.out.println("统计完成,亲查阅");
- }catch (Exception e) {
- throw new RuntimeException("文件统计失败");
- }
- finally{
- try {
- if(br!=null)
- br.close();
- } catch (IOException e) {
- throw new RuntimeException("读取流关闭失败");
- }
- try {
- if(bw!=null)
- bw.close();
- } catch (IOException e) {
- throw new RuntimeException("写入流关闭失败");
- }
- }
- }
- }
复制代码
统计前
统计后
|