如果有一个abc.txt文件
文件内容:abcd efgh I don't know
1.当其读入上述文件时,可以统计特定字母的个数。
2.这个特定的字母在创建对象时指定FileInputStream file = null;
  
  file= new FileInputStream("abc.txt");
  int len = 0;
  String temp="a";  
  int num=0;
  byte[] bt = new byte[1024];
  while((len=file.read(bt,0,1024))>0) {
  for(int i = 0; i < len; i++) {
  if(bt[i].equals(temp)) {
  num++;
  }
  }
  System.out.plint(num);
}
这样做行吗?

解决方案 »

  1.   

    public static void main(String[] args) {
            FileInputStream file = null;
            try {
                file = new FileInputStream("d:\\abc.txt");
                int len = 0;
                char temp = 'a';
                int num = 0;
                byte[] bt = new byte[1024];
                if ((len = file.read(bt, 0, 1024)) > 0) {
                    String s = new String(bt,0,len);
                    for (int i = 0; i < len; i++) {
                        if (s.charAt(i) == temp) {
                            num++;
                        }
                    }
                    System.out.println(num);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
      

  2.   

    你把整个txt读进去
    然后再用字符串的方法去处理就可以了
      

  3.   

    +1,读取出来的是每个byte对应一个char,不能直接用String比较,if ((len = file.read(bt, 0, 1024)) > 0) ,小文件可以(楼主题目就属于这种情况),如果是大文件要写成while写个通用方法比较好。
      

  4.   

    import java.io.*;public class TestIO {
    public static void main(String[] args) {
    BufferedReader br = null;
    String line = null;
    char temp = 'a';
    int count = 0;
    try{
    br = new BufferedReader(new FileReader("d:abc.txt")); //BufferedReader带缓冲区的Reader

    while((line = br.readLine())!= null) { //从文件读进一行给line
    for(int i=0; i<line.length();i++) { //对line字符串的匹配
    if(line.charAt(i)==temp)
    count ++;
    }
    }
    System.out.println(count);
    }catch(IOException e){
    e.printStackTrace();
    }finally { //最终关闭资源
    try {
    br.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }}
      

  5.   

    file= new FileInputStream("abc.txt");
      int len = 0;
      //String temp="a";
      char temp = 'a';
      int num=0;
      byte[] bt = new byte[1024];
      while((len=file.read(bt,0,1024))>0) {
      for(int i = 0; i < len; i++) {
      //if(bt[i].equals(temp)) {
      if((char)bt[i] == temp)
      num++;
      }
      }
      

  6.   

      //按字符读文件吧
      BufferedReader file = new BufferedReader(new FileReader("abc.txt"));
      char temp = 'a';
      int read = 0, num = 0;   
      while((read=file.read())!=-1) {
        if((char)read == temp) {
          num++;
        }
      }
      System.out.plint(num);