Wednesday, July 29, 2009

Use Of Scanner Class

Java 5 provides a utility class named Scanner which is very power full for parsing/Tokening any strings, Input Streams, Files, Channels.

Do not compare it with StringTokenizer utility class, this is only working with strings.

One Important feature of Scanner class is that you can parse any primitive datatype from the given strings, Input Streams, Files and Channels. 

e.g: suppose i want to take only number from the command line(InputStream), then you can use this class. the implementation of this class is very simple, there are getter methods for almost all primitive datatypes.

The constructor can take String, InputStream, File etc.

public class TestScanner

{

  public static void main(String arg[])

  {

    Scanner scan = new Scanner(System.in);

    int retNum = scan.nextInt();

    System.out.println("Yaaaa , You Have Entered :"+ retNum);

  }

}

Default delimiter for Scanner is space between two words. if you want to use another delimiter then you have to set the delimiter for that Scanner, use this Syntax:

scanner.useDelimiter(",");

e.g: if i want to get all boolean values from the scanner, then

public class FetchBooleanScanner

{

  public static void main(String arg[])

  {

    Scanner scan = new Scanner("prabir,2,true,prabirmj,3,false,raj,4,false");

    scan.useDelimiter(",");

    while(scan.hasNext())

    {

        if(scan.hasNextBoolean())

        {

           System.out.println(scan.nextBoolean());

         }

         else

         {

             scan.next();

          }

    }

  }

}

Scanner can also operate with Regular Expression using scanner object method findInLine().

public class TestScannerRegEx

{

  public static void main(String arg[])

  {

    String input = "1 persion 2 persion black  persion white persion"; 

    Scanner scan = new Scanner(input);

    scan.findInLine("(\\d+) persion (\\d+) persion (\\w+) persion (\\w+)");

    MatchResult result = scan.match();

    for (int i=1; i<=result.groupCount(); i++)

        System.out.println(result.group(i));

    scan.close(); 

  }

}


1 comment:

  1. Hi,
    It is new for me. If u add input and output section as examples then it would be more clear for me.

    ReplyDelete