Java Reference
In-Depth Information
java.nio.ReadableByteBuffer
. By default these byte sources will be con-
verted to characters using the platform's default encoding, or you can
use a form of the constructor that takes the character set name to use
as the encoding.
When the source for a scanner is a file or other input stream, it is pos-
sible that when the scanner tries to read the source it will encounter an
IOException
. The scanner methods themselves do not declare or throw
the
IOException
. The responsibility for dealing with these potential excep-
tions falls to you. If the scanner encounters an
IOException
it considers
the end of the input source to have been reachedso
hasNext
will return
false, and any attempt to take the next token will cause
NoSuchElementEx-
ception
to be thrown. To determine whether tokenizing of the source
ended because of a true end of input or an exception, you can use the
ioException
method. It returns the last
IOException
that was thrown by
the underlying source, or
null
if there have been no exceptions. So, as
in the example, when the iteration is complete you should check to see
that it didn't complete prematurely due to an exception.
A scanner identifies tokens by looking for a delimiter pattern in the
input stream of characters. By default the delimiter pattern matches any
whitespace, as determined by the
Character.isWhitespace
method. You
can set the delimiter to a different pattern with the
useDelimiter
method.
The current delimiter pattern is returned as a
Pattern
object from the
delimiter
method. For example, here is a simple method that reads val-
ues from a source that is in
comma-separated-values
(
CSV
) format and
returns them in a
List
:
public static List<String> readCSV(Readable source)
throws IOException {
Scanner in = new Scanner(source);
in.useDelimiter(",|" +LINE_SEPARATOR_PATTERN);
List<String> vals = new ArrayList<String>();
while (in.hasNext())
vals.add(in.next());
IOException ex = in.ioException();