Make fun with Text : java.util.Scanner

Scanner accepts streams, file and other string input mechanisms and parses the string and give is the tokens. (It also allows the user to specify using which encoding the text has been built). By default, whatever you have given, it is homogenized by having the default delimiter, space, See the following example,


import java.util.*;
import java.io.*;
public class test
{
    public static void main(String [] args) throws FileNotFoundException
    {
       File f = new File(“test.java”);
       Scanner scanner = new Scanner(f);
       while (scanner.hasNext())
       {
           System.out.println(scanner.next());
       }
       scanner.close();
    }
}

OutPut:


C:\>java testimport
java.util.*;
import
java.io.*;
public
class
test
{
public
static
void
main(String
[]
args)
throws
FileNotFoundException
{
File
f
=
new
File(“test.java”);
Scanner
scanner
=
new
Scanner(f);
while
(scanner.hasNext())
{
System.out.println(scanner.next());
}
scanner.close();
}
}

funny, isnt it!!!

We can also change the delimiter, see the following example


import java.util.*;

import java.io.*;
public class test
{
 public static void main(String [] args) throws FileNotFoundException
 {
 File f = new File(“test.java”);
 Scanner scanner = new Scanner(f);
 scanner.useDelimiter(“\n”);
 while (scanner.hasNext())
 {
 System.out.println(scanner.next());
 }
 scanner.close();
 }
}

The output is same as that of above code, want to see that one also?


C:\>java test
import java.util.*;
import java.io.*;
public class test
{
 public static void main(String [] args) throws FileNotFoundException
 {
 File f = new File(“test.java”);
 Scanner scanner = new Scanner(f);
 scanner.useDelimiter(“\n”);
 while (scanner.hasNext())
 {
 System.out.println(scanner.next());
 }
 scanner.close();
 }
}

Really good one!

Advertisements

About Sanju
I am Software Programmer. I am working in JAVA/J2EE Technologies.

One Response to Make fun with Text : java.util.Scanner

  1. This is the first site I read on my new Droid Tablet. I’ll be back.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: