1. 程式人生 > >寫入一個方法,輸入一個檔名和一個字串,統計這個字串在這個檔案中出現的次數。

寫入一個方法,輸入一個檔名和一個字串,統計這個字串在這個檔案中出現的次數。

public class Test1 {

/*
 * 
 * 寫一個方法,輸入一個檔名和一個字串,統計這個字串在這個檔案中出現的次數。
 * 
 */

public static void main(String[] args) {
    // TODO Auto-generated method stub

 String filePath = "D:/abc.txt" ;
 System.out.println("結果:" + countWordInFile(filePath, "愛"));


}



 /** 
 * 統計給定檔案中給定字串的出現次數 
 *  
 * @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;  
    }
}