統計這個字串在這個檔案中出現的次數。
阿新 • • 發佈:2019-02-17
import java.io.BufferedReader;
import java.io.FileReader;
public final class MyUtil {
// 工具類中的方法都是靜態方式訪問的因此將構造器私有不允許建立物件(絕對好習慣)
private MyUtil() {
throw new AssertionError();
}
/**
* 統計給定檔案中給定字串的出現次數
*
* @param filename 檔名
* @param word 字串
* @return 字串在檔案中出現的次數
*/
public static int countWordInFile(String filename, String word) {
int counter = 0;
try (FileReader fr = new FileReader(filename)) {
try (BufferedReader br = new BufferedReader(fr)) {
String line = null;
while ((line = br.readLine()) != null ) {
int index = -1;
while (line.length() >= word.length() && (index = line.indexOf(word)) >= 0) {
counter++;
line = line.substring(index + word.length());
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return counter;
}
}