讀取txt文件,獲取指定字符串出現的次數

package com.xjh.demo.exam;

import java.io.*;

/**
 * 給定一個txt文件,如何得到某字符串出現的次數
 */
public class StringCount {

    public static void main(String[] args) {
        String filePath = "D:\\a.txt";
        File file = new File(filePath);
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "GBK"));
            String temp = null;
            String result = "";
            while ((temp = bufferedReader.readLine()) != null) {
                result += temp;
            }
            bufferedReader.close();
            System.out.println(result);
            int index = 0;
            int count = 0;
            String specialStr = "d";
            int len = specialStr.length();
            while ((index=result.indexOf(specialStr, index)) != -1) {
                index += len;
                count++;
            }
            System.out.println(count);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章