THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

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 values from a source that is in comma-separated-values (CSV) format and returns them in a
List:


public static List readCSV(Readable source)
throws IOException {
Scanner in = new Scanner(source);
in.useDelimiter(",|" +LINE_SEPARATOR_PATTERN);
List vals = new ArrayList();


while (in.hasNext())
vals.add(in.next());


IOException ex = in.ioException();
if (ex!= null)
throw ex;


return vals;
}


Here the delimiter pattern is either a single comma or a line separator, since the values themselves can contain
any other characters, including whitespace. The definition of a line separator is documented in the Pattern
class. To make it easier to read the example, we defined a constant to represent that pattern:


static final String LINE_SEPARATOR_PATTERN =
"\r\n|[\n\r\u2028\u2029\u0085]";


The Scanner class also provides a close method. When you invoke close on a scanner, the input source
will be closed if it is Closeable. Once a scanner has been closed, attempts to invoke any of the scanning
operations will result in an IllegalStateException. Take care when closing a scanner: The input
source may not be yours to close, such as an InputStreamReader for System.in. As a general rule,
don't close a scanner unless you opened its input source.


22.5.2. Scanning Lines


In line mode, the scanner can process a line at a time using the regular expression pattern that you supply. If
the line matches the pattern then a java.util.regex.MatchResult object can be obtained from the
match method, from which you can extract the groups the pattern defined. Line matching is done with the
findInLine method.


public String findInLine(Pattern pattern)

Attempts to find the given pattern before the next line separator is
encountered. The delimiters of the scanner are ignored during this search. If
the pattern is found then the scanner advances to the next position after the
matching input, and the matching input is returned. If the pattern is not found
Free download pdf