Make fun with Text : java.util.Scanner


One of my friend came with the sun’s newsletter today morning. I was wondering about their demo on a new class, java.util.Scanner
See, parsing the string becomes very simple, like iterating a list.

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. goo news for localisation guyz like me). By default, whatever you have given, it is tokenized 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();
}
}

The output is

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);
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! But I really miss the fun of using the streams 😦

Advertisements

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