package com.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class Count {
public void count(File file){
//存储字符的Map
Map map = new HashMap();
//输入输出流
BufferedReader reader = null;
PrintWriter writer = null;
try {
reader = new BufferedReader(new FileReader(file));
writer = new PrintWriter(new FileWriter(new File("E:\\count.txt"),true));//true表明可以在文件末尾追加
String line = null;
while( (line=reader.readLine())!=null ){//每次读取一行
char[] l = line.toCharArray();//转为char数组遍历
for(int i=0;i
if(l[i]==' '||l[i]=='\n'||l[i]=='\t'){//不计算空格等
}else if( map.get(l[i])==null ){//为null说明是第一次出现
map.put(l[i], 1);
}else{//在原来的基础上加1
map.put(l[i], map.get(l[i])+1);
}
}
}
Iterator it = map.keySet().iterator();//用迭代器遍历Map
while(it.hasNext()){
char key = it.next();//得到key
writer.append(key + "-->" + map.get(key));//存储到文件
writer.println();//换行
writer.flush();
}
} catch (Exception e) {
System.out.println("出现异常,未能正常统计");
} finally{
try {
reader.close();//关闭流
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("字数统计完毕");
}
public static void main(String[] args) throws Exception {
Count count = new Count();
count.count(new File("E:\\test.txt"));
}
}
看不合不合要求,只是实现了,可能性能不怎么好