1. 程式人生 > >文件讀取,輸入一個單詞查找文件裏有多少個

文件讀取,輸入一個單詞查找文件裏有多少個

gen [] 運行 void ava 圖片 分享圖片 buffer pac

代碼

package TestNumber;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class FileWordCount {

    public static void checkWord(String file,String word) throws IOException {
        
        //由於是可讀字符文件
        FileReader fr=new FileReader(new File(file));
        BufferedReader bfr=new BufferedReader(fr);
        int count=0;
        String str="";
        //每次讀取一行
        while((str=bfr.readLine())!=null) {
            int len=str.indexOf(word);
            //讀取每一行裏有沒有這個單詞
            while(len!=-1) {
              count++;
              //
              len=str.indexOf(word,len+word.length()-1);
            }
        }
        System.out.println("文件中存在"+count+"個"+word);
    }
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub

        Scanner sc=new Scanner(System.in);
        System.out.println("請輸入文件路徑:");
        String file=sc.nextLine();
        while(true) {
            System.out.println("請輸入要查找的單詞:");
            String word=sc.nextLine();
            checkWord(file,word);
        }
    }
}

運行效果

技術分享圖片

技術分享圖片

文件讀取,輸入一個單詞查找文件裏有多少個