BufferReader readLine()问题:直到文件末尾才搜索

时间:2015-09-16 07:41:43

标签: java

我正在文件中搜索特定的关键字。我希望它会打印文件的所有出现(count ++)。但它只打印一次出现,如果关键字出现在第二次出现相同的行但不打印下一行中存在的所有关键字。

    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 StringFinder {

    public static void main(String[] args) throws FileNotFoundException
    {
        double count = 0,countBuffer=0,countLine=0;
        String  lineNumber = "";
        String filePath = "C:\\IBM\\Project\\TestText.txt";
        String inputSearch = "public";
        String line = null;


          BufferedReader  br = new BufferedReader(new FileReader(filePath));
            //Scanner file = new Scanner(new File("filepath"));
            try {

                {
                while((line = br.readLine()) != null )

                {
                    countLine++;
                    String[] words = line.split(" ");
                    for (String word : words) 
                    {
                      if (word.equals(inputSearch)) 
                      {
                          System.out.println(word);
                        count++;
                        countBuffer++;
                      }
                    }

                    if(countBuffer > 0)
                    {
                        countBuffer = 0;
                        lineNumber += countLine + ",";
                    }

                }
                br.close();
                }      
            } catch (Exception e) {

                e.printStackTrace();
            }

        System.out.println("Times foun`enter code here`d at--"+count);
        System.out.println("Word found at--"+lineNumber);
    }
    }

输出

public
public
Times found at--2.0//two times because both keyword are in same line
Word found at--3.0,//both keyword are in line no 3

但在第3.0行之后它不会打印。

由于

0 个答案:

没有答案