In
the previous part I have discussed about streams(Input and Output),
PrintStream, BufferedReader, InputStreamReader Class and publicized how to take
input from console.
In
these section I'm going to discuss about One more class called Scanner.A Scanner breaks its input into tokens using a delimiter
pattern, which by default matches whitespace. The resulting tokens may then be
converted into values of different types using the various next methods.
in
regular words.Scanner reads formatted input and converts it into binary form.
Addition of Scanner class in JDK 5 makes it easier now to read all types of
numeric values, Strings, and other types of data ,whether it comes from disk
file, the Keyboard or from another source.
The
structure of the Scanner class is
public final class Scanner
extends
Object
implements
Iterator<String>
There
are two constructors that are particularly useful: one takes
an InputStream object
as
a parameter and the other takes a FileReader object as a parameter.
Scanner
in = new Scanner(System.in); // System.in is an InputStream
Scanner
inFile = new Scanner(new FileReader("myFile"));
If
the file ≥myFile≤ is not found, a FileNotFoundException is
thrown.
This is a checked exception, so it must be caught or forwarded by
putting
the phrase ≥throws FileNotFoundException≤ on the header of the method
in
which the instantiation occurs and the header of any method that calls the
method
in which the instantiation occurs.
Numeric
and String Methods
Method
|
Returns
|
int
nextInt()
|
Returns
the next token as an int. If the next token is not an
integer,InputMismatchException is thrown.
|
long
nextLong()
|
Returns
the next token as a long. If the next token is not an
integer,InputMismatchException is thrown.
|
float
nextFloat()
|
Returns
the next token as a float. If the next token is not a float or is out of
range, InputMismatchException is thrown.
|
double
nextDouble()
|
Returns
the next token as a long. If the next token is not a float or is out of
range, InputMismatchException is thrown.
|
String
next()
|
Finds and
returns the next complete token from this scanner and returns it as a string;
a token is usually ended by whitespace such as a blank or line break. If not
token exists,NoSuchElementException is thrown.
|
String
nextLine()
|
Returns
the rest of the current line, excluding any line separator at the end.
|
void
close()
|
Closes the
scanner.
|
The Scanner looks
for tokens in the input. A token is a series of characters
that
ends with what Java calls whitespace. A whitespace character
can
be a blank, a tab character, a carriage return, or the end of the file.
Thus,
if we read a line that has a series of numbers separated by blanks, the
scanner
will take each number as a separate token. Although we have only shown
four numeric
methods,
each numeric data type has a corresponding method that reads values of that
type.
The
numeric values may all be on one line with blanks between each value or may be
on separate
lines.
Whitespace characters (blanks or carriage returns) act as
separators.The next method returns
the
next input value as a string, regardless of what is keyed.
For
example,given the following code segment.
int number = in.nextInt();
float real = in.nextFloat();
long number2 = in.nextLong();
double real2 = in.nextDouble();
String string = in.next();
Here
is a program that uses these methods, followed by the output. Look
over the application carefully to be sure you understand how the output was
generated.
//**********************************************************************
//
Class NumericInput demonstrates reading numeric values.
//**********************************************************************
import java.util.Scanner;
import java.io.*; // Access System.out
public class NumericInput
{
public static void main(String[]
args)
{
// Declarations
Scanner
in = new Scanner(System.in);
int integer;
long longInteger;
float realNumber;
double doubleReal;
String
string1;
String
string2;
// Prompts
System.out.println("Enter an
integer, a long integer, " + "a floating-point ");
System.out.println("number, another
floating-point number, "+ "and a string.");
System.out.println("Separate each
with a blank or return.");
//
Read in values
integer
= in.nextInt();
longInteger
= in.nextLong();
realNumber
= in.nextFloat();
doubleReal
= in.nextDouble();
string1
= in.nextLine();
System.out.println("Now enter
another value.");
string2
= in.next();
System.out.println("Here is what you
entered: ");
System.out.println(integer
+ "
" +
longInteger + "
" +
realNumber + "
" +
doubleReal + "
"
+ string1 + " and " + string2);
}
}
Output:
Enter
an integer, a long integer, a floating-point
number,
another floating-point number, and a string.
Separate
each with a blank or return.
23
24
25.0
233333333333333.444 Hello
Now
enter another value.
23.4
Here
is what you entered:
23
24 25.0 2.3333333333333344E14 Hello and 23.4
What
would happen if there were no token in the file in the previous example?
Each
of the boolean methods would
return false. They return true if and only if the
next token in the
scanner
can be interpreted as a value of their type. We return to the subject of
reading data from
files
later in this chapter and show how to use these Scanner methods
to allow us to read multiple
values
from a line in a file. Except for some trivial cases, we must
combine
reading operations with loops to read through all of the data on a file.
Files
To
read from a file rather than the keyboard, you instantiate
a Scanner object
with
a FileReader object rather than System.in.
Scanner
in = new Scanner(System.in); //
Reading from the keyboard
Scanner
inFile = new Scanner(new FileReader(≥inFile.dat≤)); // Reading from a file
Although
all of the methods applied to keyboard input can be applied to file input,
there
are methods that are usually applied only to files. These are the methods that
ask
of there are more values in the file. If there are no more values in a file, we
say that
the
file is at the end of the file (EOF). For example,
inFile.hasNext();
inFile.hasNextLine();
return true if inFile has
another token in the file or if there is another line in the file.
What
about the methods hasNextInt and so forth that we used to look ahead
at the
type
of the next input token? These can be used to determine if there are more
data values
in
the file, provided you know exactly how the files are organized
Be
sure to close all files. If you forget to close System.in,
no
harm is done, but forgetting to close a file can cause problems.
Difference between Scanner and
BufferedReader
Though
both are meant for standard input but Scanner is used for parsing tokens from
the contents of the stream while BufferedReader just reads the stream and does
not do any special parsing.
·
BufferedReader
is synchronized and Scanner is not, so its up to you to decide.
·
The
Scanner has a little buffer (1KB char buffer) as opposed to the BufferedReader
(8KB byte buffer), but it's more than enough.
·
Scanner
is memory/cpu heavy (at least when compared to BufferedReader) because it
internally uses "regular expressions" for matching your
"nextXXX" as opposed to just reading everything till the end of line
as in the case of a regular Reader.
·
Scanner
can use tokenize using custom delimiter and parse the stream into primitive
types of data, while BufferedReader can only read and store String.