統計ファイル内の文字列の出現回数

1345 ワード

public static void main(String[] args) throws Exception{
        String word = " ";
        String path = "D:/file/file.txt";
        int occurTime = occurTime(path, word);
        System.out.println(occurTime);
    }


// 
    public static int occurTime(String path,String word) throws Exception {
        BufferedReader br = new BufferedReader(new FileReader(path));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null){
            sb.append(line);
        }
        String text = sb.toString();
        // word , , 
        boolean isWordStart = text.startsWith(word);
        if (isWordStart){
            if ("a".equals(word)){
                text = "b".concat(word);
            }else {
                text = "a".concat(word);
            }
        }
        boolean isWordEnd = text.endsWith(word);
        if (isWordEnd){
            if ("a".equals(word)){
                text = text.concat("b");
            }else {
                text = text.concat("a");
            }
        }
        String[] splitString = text.split(word);
        int occurTime = splitString.length - 1;
//        System.out.println(" =" + occurTime);
        return occurTime;
    }