本帖最后由 晓恣晴空 于 2014-10-13 16:25 编辑
还是先把答案贴出来public class Test01 {
/**
* 写一个txt文档(全是字母),读取txt文档的内容,统计各个字母的个数,并把统计情况保存到一个a.txt文档里
* @param args
*/
public static void main(String[] args) {
File fileName=new File("src.txt");
File toFileName=new File("dest.txt");
countFunc(fileName,toFileName);
}
public static void countFunc(File fileName,File toFileName){
BufferedReader br=null;
BufferedWriter bw=null;
FileInputStream fi;
try {
fi = new FileInputStream(fileName);
InputStreamReader is= new InputStreamReader(fi, "GBK");
br=new BufferedReader(is);
TreeMap<Character,Integer> tm=new TreeMap<Character, Integer>();
String line=null;
while((line=br.readLine())!=null){
char[] ch=line.toCharArray();
for(int i=0;i<ch.length;i++){
if(tm.containsKey(ch)){
tm.put(ch, tm.get(ch)+1);
}else{
tm.put(ch, 1);
}
}
}
FileOutputStream fs=new FileOutputStream(toFileName);
OutputStreamWriter ow=new OutputStreamWriter(fs,"GBK");
bw=new BufferedWriter(ow);
Set<Map.Entry<Character,Integer>> entrySet=tm.entrySet();
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 (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try{
if(br!=null){
br.close();
}
}catch(IOException e){
System.out.println("读取流关闭失败");
}
try{
if(bw!=null){
bw.close();
}
}catch(IOException e){
System.out.println("写入流关闭失败");
}
}
}
}
写的比较仓促,不完善,后期修改吧
|