且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

计算字符串在文件中出现的次数

更新时间:2021-11-22 21:39:08

您在这里:

public int countStringInFile(String stringToLookFor, String fileName){
  int count = 0;
  try{
    FileInputStream fstream = new FileInputStream(fileName);
    DataInputStream in = new DataInputStream(fstream);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;
    while ((strLine = br.readLine()) != null)   {
      int startIndex = strLine.indexOf(stringToLookFor);
      while (startIndex != -1) {
        count++;
        startIndex = base.indexOf(stringToLookFor, 
                                  startIndex +stringToLookFor.length());
      }
    }
    in.close();
  }catch (Exception e){//Catch exception if any
    System.err.println("Error: " + e.getMessage());
  }
  return count;
}

用法:int count = countStringInFile("SomeWordToLookFor", "FileName");