请教一个关于统计文档里字符个数的问题,下面是代码:
import java.io.*;
public class Test{

public static void main(String args[]) throws IOException,ClassNotFoundException{
FileReader fr = null;
int i = 0;
try{
File file = new File("d:/123.txt");
fr = new FileReader(file);
    
BufferedReader br = new BufferedReader(fr);
String s = br.readLine();  //这里调用readLine方法



for(int j = 0;j < s.length();j++){
   if(s.charAt(j) == 's')
    i++;

}



}catch (IOException e){

}finally {
System.out.println("s: " + i);  //打出字符出现个数。
}
}
}这段代码只能统计一行里出现多少个字符,如果我想统计
全部的字符(包括换行的其它字符),请问该怎么解决,
请大家帮帮忙!

解决方案 »

  1.   

    public static int statChar(String fileName)throws IOException{
    File file=new File(fileName);
    BufferedReader br=new BufferedReader(new FileReader(file));
    String s=null;
    int total=0;
    while((s=br.readLine())!=null){
    total+=s.length();
    }
    return total;
    }
      

  2.   

    不要用readLine,直接用字符流逐个字符读取,然后进行比较
      

  3.   

    import java.io.*;
    public class Test{public static void main(String args[]) throws IOException,ClassNotFoundException{
    FileReader fr = null;
    int i = 0;
    try{
    File file = new File("d:/123.txt");
    fr = new FileReader(file);
        
    BufferedReader br = new BufferedReader(fr);
    String s= null;  //这里调用readLine方法while((s = br.readLine()) != null){
    for(int j = 0;j < s.length();j++){
       if(s.charAt(j) == 's')
       i++;}
    }
    }catch (IOException e){}finally {
    System.out.println("s: " + i);  //打出字符出现个数。
    }
    }
    }