Java newbie: infinite loop to find specific text in a file

I need to find a line at a specific line in a text file that is multiple lines of lines. However, my loop for finding text or end of file is always looking. I know the line is in the file. Here is the code I'm using to find the text - but be careful, if you try it on your system, even with a simple text file, it will go into a perpetual loop.

I really appreciate any advice or pointers to explain what I am doing wrong here.

private static void locateText(String locateText, BufferedReader locateBffer) {
    boolean unfound = true;
    try
    {
        String line = locateBffer.readLine();
        while (unfound)
        {
            line = locateBffer.readLine();
            if ((line.equals(locateText)) || (line == null))
            {
                unfound = false;
            }
        }
    }
    catch(IOException e)
    {
        System.out.println("I/O error in locateText");
    }
}

      

Update: Found a problem - it didn't find a match on the first line of the file.

+2


source to share


3 answers


Your text can be found on the first line, by any chance? You are doing a readLine operation outside of your loop and then inside, so the first line is mostly ignored.



+4


source


I think GaryF is right (your text is on the first line of your file).

I wanted to specify a line in your code:

if ((line.equals(locateText)) || (line == null)) {

      

you have to write this:



if ((line == null) || (line.equals(locateText)) {

      

Indeed, if the string is zero, your code will throw a NullPointerException. This is why you should check if there is one line

null

before.

In addition to this, I suggest you familiarize yourself with the Apache commons.lang library as it provides some pretty useful classes for text (e.g. StringUtils) ...

+5


source


Change this loop to something like this and it will read all lines:

while((line = locateBffer.readLine()) != null){
 if(line.equals(locateText)){
     break;  
 }
}

      

Maybe this will help.

0


source







All Articles