通过读取硬盘中的文档,来统计该文档中指定字符的个数,并对指定字符进行替换

文章引用于:http://zhidao.baidu.com/question/57065041.html

import java.io.*;

public class MyTest2 { 

     public static void main(String[] args) { 
          MyTest2 test = new MyTest2(); 
          test.countCharacter(); 
     } 

     public void countCharacter(){ 
          String file = "e:\\1.txt"; 
          String file2 = "e:\\2.txt"; 
          try { 
               BufferedReader br = new BufferedReader(new FileReader(file)); 
               BufferedWriter bw = new BufferedWriter(new FileWriter(file2)); 
               String line = null; 
               int tot = 0;//用来统计数,假如这里统计字母a的出现次数 
               int index = 0; 
               while((line=br.readLine()) != null){ 
                    for (int i = 0; i < line.length(); i++) { 
                         if(line.substring(i,(i+1)).equals("a")){ 
                              tot++; 
                         } 

                    } 
                    char emp = 'b'; 
                    char emp1 = 'x'; 
                    String line1 = line.replaceAll("bc","c");//将"bc"替换成"c" 
                    bw.write(line1); 
                    bw.write("\r\n"); 
               } 
               System.out.println("字符a在文中出现的次数是:" + tot); 
               br.close(); 
               bw.close(); 
          } 
          catch (Exception e) { 
               System.out.println(e.getMessage()); 
          } 
     }
}

posted on 2008-11-26 21:06  黄洪汉  阅读(216)  评论(0编辑  收藏  举报