Chi
Chi

Reputation: 7

Java reuse scanner

I'm trying to extract string from txt file with matching data with the problem below

when I'm trying to reuse my scanner it consume all the resources and got stuck in the page

String tmpStr1 = scanStr("Name :",streamData);
String tmpStr2 = scanStr("Email :",streamData); //it got stuck on this line

public String scanStr(String Str, String fileData){
    Scanner s = new Scanner(fileData);
    while (s.hasNextLine()) {
        try{
            s.findInLine(Str+" (\\S*)(.*)");
            if(s.match()!=null) { 
                MatchResult result = s.match();
                s.close();
                return result.group(1);
            }
            s.nextLine();
        } catch (IllegalStateException e){

        }
    }
    s.close();
    return "";
}

Is there any way to solve this problem? Many thanks.

Upvotes: 0

Views: 1738

Answers (1)

user207421
user207421

Reputation: 311052

  1. You need to advance to the next line if no match, with nextLine(). Otherwise the Scanner's position is unchanged and you will scan the same line forever.

  2. Scanner.match() doesn't return null if there is no match. It throws IllegalStateException. See the Javadoc. Ergo testing it for null is pointless. What you should be testing is whether findInLine() returned null. Then you can get rid of the catch (IllegalStateException ...) block.

  3. Returning "" is almost always a bad idea, and this is no exception. You should return null, indicating no match. "" would indicate an empty name or e-mail address. You need to be able to distinguish the two.

Revised, also using better variable names:

public static String scanStr(String prefix, String data)
{
    try (Scanner s = new Scanner(data))
    {
        while (s.hasNextLine())
        {
            if (s.findInLine(prefix + " (\\S*)(.*)") != null)
            {
                return s.match().group(1);
            }
            s.nextLine();
        }
        return null;
    }
}

There is no Scanner re-use here, nor should there be.

Upvotes: 1

Related Questions