views:

321

answers:

3

I'm needing to locate a string on a particular line in a text file that is composed of several lines of strings. However, my loop to find the text or the end of the file is eternally searching. I know the string is in the file. Here is the code I am using to locate the text - but be warned, if you try it on your system even with a simple text file it will go into an eternal loop.

I very much appreciate any tips or pointers to explain what I'm 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 the problem - it was not finding the match on the first line of the file.

+4  A: 

Is your text to find in the first line, by any chance? You do a readLine operation outside of your loop and then inside, so the first line basically gets ignored.

GaryF
A good and valuable answer, but how does that cause an infinite loop?
RichieHindle
Thanks very much Gary. Yes, the first line of the file contained the text. I changed String line = locateBffer.readLine(); to read String line = ""; and that solved the problem.
elwynn
A: 

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

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

Maybe that will help.

pir0
+4  A: 

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

I wanted to point a line in your code:

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

you must instead write this:

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

Indeed, if line is null, your code will throw a NullPointerException. That's why you must test if line is null before.

In addition to that, I suggest that you have a look in commons.lang library of Apache, as it provides quite usefull classes for text (like StringUtils)...

romaintaz
Thank you for the tip. I will alter the code accordingly!
elwynn