統計文件中指定字符串的個數

public class StringCountInFile {
    public static void main(String[] args) {
        //獲取當前項目的路徑
        //System.out.println(System.getProperty("user.dir"));
        System.out.println(countStrInFile2("src/niuke/test.txt", "o"));
    }

    /**
     * 統計指定字符串在文件中出現的次數
     * 正則表達式
     * 是區分大小寫的
     * @param filename
     * @param str
     */
    public static int countStrInFile(String filename,String str){
        int count = 0;
        //讀取指定路徑的文件 fileReader
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
            String line ;
            StringBuffer fileStr = new StringBuffer();
            while ((line = br.readLine()) != null){
                fileStr = fileStr.append(line);
            }
            String patten = ".*"+str+".*";
            while (true){
                //當字符串中沒有str字串,退出循環
                if (Pattern.matches(patten,fileStr)){
                    //次數加1
                    count ++;
                    //從大串中刪除字串
                    int start = fileStr.indexOf(str);
                    //左閉右開
                    fileStr.delete(start,start+str.length());
                }
                else {
                    break;
                }

            }


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //返回次數
        return count;
    }
    /**
     * 統計指定字符串在文件中出現的次數
     *
     * @param filename
     * @param str
     */
    public static int countStrInFile2(String filename,String str){
        int count2 = 0;
        try {
            //創建輸入緩衝流
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
            //創建可變字符串
            StringBuilder sb = new StringBuilder();
            //每一次讀取一行,加入到可變字符串
            String line;
            while ((line = br.readLine()) != null){
                sb = sb.append(line);
            }
            //每次找到一個就從大字符串中刪除
            while (sb.indexOf(str) != -1){
                count2 ++;
                int start = sb.indexOf(str);
                sb.delete(start,start+str.length());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return count2;
    }
    
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章