統計字串在檔案中出現的次數
阿新 • • 發佈:2018-11-16
話不多說直接上程式碼
package Test; import java.io.BufferedReader; import java.io.FileReader; /** * 寫一個方法輸入一個一個檔名和一個字串,統計這個字串出現的次數 * @author Administrator * */ public final class MyUtil { //測試方法 public static void main(String[] args) { System.out.println(MyUtil.countWordInFile("E:\\course.txt", "Workbench")); } // 工具類中的方法都是靜態方式訪問的因此將構造器私有不允許建立物件(絕對好習慣) 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)) { System.out.println("br="+br); 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; } }