Scanner.java revision 893
869N/A/*
869N/A * Copyright 2003-2009 Sun Microsystems, Inc. All Rights Reserved.
869N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
869N/A *
869N/A * This code is free software; you can redistribute it and/or modify it
869N/A * under the terms of the GNU General Public License version 2 only, as
869N/A * published by the Free Software Foundation. Sun designates this
869N/A * particular file as subject to the "Classpath" exception as provided
869N/A * by Sun in the LICENSE file that accompanied this code.
869N/A *
869N/A * This code is distributed in the hope that it will be useful, but WITHOUT
869N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
869N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
869N/A * version 2 for more details (a copy is included in the LICENSE file that
869N/A * accompanied this code).
869N/A *
869N/A * You should have received a copy of the GNU General Public License version
873N/A * 2 along with this work; if not, write to the Free Software Foundation,
869N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
869N/A *
869N/A * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
869N/A * CA 95054 USA or visit www.sun.com if you need additional information or
869N/A * have any questions.
869N/A */
869N/A
0N/Apackage java.util;
0N/A
0N/Aimport java.nio.file.FileRef;
0N/Aimport java.util.regex.*;
869N/Aimport java.io.*;
0N/Aimport java.math.*;
0N/Aimport java.nio.*;
0N/Aimport java.nio.channels.*;
869N/Aimport java.nio.charset.*;
0N/Aimport java.text.*;
869N/Aimport java.util.Locale;
0N/Aimport sun.misc.LRUCache;
869N/A
869N/A/**
869N/A * A simple text scanner which can parse primitive types and strings using
0N/A * regular expressions.
869N/A *
48N/A * <p>A <code>Scanner</code> breaks its input into tokens using a
869N/A * delimiter pattern, which by default matches whitespace. The resulting
0N/A * tokens may then be converted into values of different types using the
869N/A * various <tt>next</tt> methods.
716N/A *
869N/A * <p>For example, this code allows a user to read a number from
0N/A * <tt>System.in</tt>:
0N/A * <blockquote><pre>
869N/A * Scanner sc = new Scanner(System.in);
868N/A * int i = sc.nextInt();
983N/A * </pre></blockquote>
1004N/A *
1007N/A * <p>As another example, this code allows <code>long</code> types to be
869N/A * assigned from entries in a file <code>myNumbers</code>:
869N/A * <blockquote><pre>
1004N/A * Scanner sc = new Scanner(new File("myNumbers"));
0N/A * while (sc.hasNextLong()) {
0N/A * long aLong = sc.nextLong();
869N/A * }</pre></blockquote>
868N/A *
0N/A * <p>The scanner can also use delimiters other than whitespace. This
0N/A * example reads several items in from a string:
65N/A *<blockquote><pre>
869N/A * String input = "1 fish 2 fish red fish blue fish";
868N/A * Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
65N/A * System.out.println(s.nextInt());
869N/A * System.out.println(s.nextInt());
65N/A * System.out.println(s.next());
65N/A * System.out.println(s.next());
65N/A * s.close(); </pre></blockquote>
65N/A * <p>
65N/A * prints the following output:
65N/A * <blockquote><pre>
65N/A * 1
65N/A * 2
65N/A * red
65N/A * blue </pre></blockquote>
65N/A *
65N/A * <p>The same output can be generated with this code, which uses a regular
65N/A * expression to parse all four tokens at once:
65N/A *<blockquote><pre>
65N/A * String input = "1 fish 2 fish red fish blue fish";
0N/A * Scanner s = new Scanner(input);
869N/A * s.findInLine("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)");
868N/A * MatchResult result = s.match();
0N/A * for (int i=1; i<=result.groupCount(); i++)
0N/A * System.out.println(result.group(i));
0N/A * s.close(); </pre></blockquote>
0N/A *
0N/A * <p>The <a name="default-delimiter">default whitespace delimiter</a> used
0N/A * by a scanner is as recognized by {@link java.lang.Character}.{@link
0N/A * java.lang.Character#isWhitespace(char) isWhitespace}. The {@link #reset}
869N/A * method will reset the value of the scanner's delimiter to the default
0N/A * whitespace delimiter regardless of whether it was previously changed.
0N/A *
869N/A * <p>A scanning operation may block waiting for input.
868N/A *
0N/A * <p>The {@link #next} and {@link #hasNext} methods and their
0N/A * primitive-type companion methods (such as {@link #nextInt} and
869N/A * {@link #hasNextInt}) first skip any input that matches the delimiter
0N/A * pattern, and then attempt to return the next token. Both <tt>hasNext</tt>
0N/A * and <tt>next</tt> methods may block waiting for further input. Whether a
869N/A * <tt>hasNext</tt> method blocks has no connection to whether or not its
868N/A * associated <tt>next</tt> method will block.
869N/A *
869N/A * <p> The {@link #findInLine}, {@link #findWithinHorizon}, and {@link #skip}
868N/A * methods operate independently of the delimiter pattern. These methods will
868N/A * attempt to match the specified pattern with no regard to delimiters in the
869N/A * input and thus can be used in special circumstances where delimiters are
869N/A * not relevant. These methods may block waiting for more input.
0N/A *
0N/A * <p>When a scanner throws an {@link InputMismatchException}, the scanner
48N/A * will not pass the token that caused the exception, so that it may be
869N/A * retrieved or skipped via some other method.
869N/A *
869N/A * <p>Depending upon the type of delimiting pattern, empty tokens may be
868N/A * returned. For example, the pattern <tt>"\\s+"</tt> will return no empty
869N/A * tokens since it matches multiple instances of the delimiter. The delimiting
868N/A * pattern <tt>"\\s"</tt> could return empty tokens since it only passes one
869N/A * space at a time.
0N/A *
0N/A * <p> A scanner can read text from any object which implements the {@link
869N/A * java.lang.Readable} interface. If an invocation of the underlying
868N/A * readable's {@link java.lang.Readable#read} method throws an {@link
0N/A * java.io.IOException} then the scanner assumes that the end of the input
0N/A * has been reached. The most recent <tt>IOException</tt> thrown by the
848N/A * underlying readable can be retrieved via the {@link #ioException} method.
848N/A *
848N/A * <p>When a <code>Scanner</code> is closed, it will close its input source
869N/A * if the source implements the {@link java.io.Closeable} interface.
868N/A *
848N/A * <p>A <code>Scanner</code> is not safe for multithreaded use without
0N/A * external synchronization.
0N/A *
0N/A * <p>Unless otherwise mentioned, passing a <code>null</code> parameter into
869N/A * any method of a <code>Scanner</code> will cause a
0N/A * <code>NullPointerException</code> to be thrown.
0N/A *
0N/A * <p>A scanner will default to interpreting numbers as decimal unless a
868N/A * different radix has been set by using the {@link #useRadix} method. The
868N/A * {@link #reset} method will reset the value of the scanner's radix to
868N/A * <code>10</code> regardless of whether it was previously changed.
868N/A *
869N/A * <a name="localized-numbers">
868N/A * <h4> Localized numbers </h4>
115N/A *
868N/A * <p> An instance of this class is capable of scanning numbers in the standard
868N/A * formats as well as in the formats of the scanner's locale. A scanner's
868N/A * <a name="initial-locale">initial locale </a>is the value returned by the {@link
868N/A * java.util.Locale#getDefault} method; it may be changed via the {@link
868N/A * #useLocale} method. The {@link #reset} method will reset the value of the
869N/A * scanner's locale to the initial locale regardless of whether it was
868N/A * previously changed.
868N/A *
868N/A * <p>The localized formats are defined in terms of the following parameters,
868N/A * which for a particular locale are taken from that locale's {@link
868N/A * java.text.DecimalFormat DecimalFormat} object, <tt>df</tt>, and its and
868N/A * {@link java.text.DecimalFormatSymbols DecimalFormatSymbols} object,
868N/A * <tt>dfs</tt>.
869N/A *
868N/A * <blockquote><table>
868N/A * <tr><td valign="top"><i>LocalGroupSeparator&nbsp;&nbsp;</i></td>
868N/A * <td valign="top">The character used to separate thousands groups,
868N/A * <i>i.e.,</i>&nbsp;<tt>dfs.</tt>{@link
868N/A * java.text.DecimalFormatSymbols#getGroupingSeparator
869N/A * getGroupingSeparator()}</td></tr>
868N/A * <tr><td valign="top"><i>LocalDecimalSeparator&nbsp;&nbsp;</i></td>
868N/A * <td valign="top">The character used for the decimal point,
868N/A * <i>i.e.,</i>&nbsp;<tt>dfs.</tt>{@link
868N/A * java.text.DecimalFormatSymbols#getDecimalSeparator
868N/A * getDecimalSeparator()}</td></tr>
869N/A * <tr><td valign="top"><i>LocalPositivePrefix&nbsp;&nbsp;</i></td>
868N/A * <td valign="top">The string that appears before a positive number (may
868N/A * be empty), <i>i.e.,</i>&nbsp;<tt>df.</tt>{@link
868N/A * java.text.DecimalFormat#getPositivePrefix
868N/A * getPositivePrefix()}</td></tr>
868N/A * <tr><td valign="top"><i>LocalPositiveSuffix&nbsp;&nbsp;</i></td>
868N/A * <td valign="top">The string that appears after a positive number (may be
868N/A * empty), <i>i.e.,</i>&nbsp;<tt>df.</tt>{@link
869N/A * java.text.DecimalFormat#getPositiveSuffix
868N/A * getPositiveSuffix()}</td></tr>
868N/A * <tr><td valign="top"><i>LocalNegativePrefix&nbsp;&nbsp;</i></td>
868N/A * <td valign="top">The string that appears before a negative number (may
868N/A * be empty), <i>i.e.,</i>&nbsp;<tt>df.</tt>{@link
868N/A * java.text.DecimalFormat#getNegativePrefix
868N/A * getNegativePrefix()}</td></tr>
868N/A * <tr><td valign="top"><i>LocalNegativeSuffix&nbsp;&nbsp;</i></td>
869N/A * <td valign="top">The string that appears after a negative number (may be
868N/A * empty), <i>i.e.,</i>&nbsp;<tt>df.</tt>{@link
0N/A * java.text.DecimalFormat#getNegativeSuffix
869N/A * getNegativeSuffix()}</td></tr>
0N/A * <tr><td valign="top"><i>LocalNaN&nbsp;&nbsp;</i></td>
868N/A * <td valign="top">The string that represents not-a-number for
869N/A * floating-point values,
868N/A * <i>i.e.,</i>&nbsp;<tt>dfs.</tt>{@link
0N/A * java.text.DecimalFormatSymbols#getNaN
869N/A * getNaN()}</td></tr>
0N/A * <tr><td valign="top"><i>LocalInfinity&nbsp;&nbsp;</i></td>
868N/A * <td valign="top">The string that represents infinity for floating-point
869N/A * values, <i>i.e.,</i>&nbsp;<tt>dfs.</tt>{@link
868N/A * java.text.DecimalFormatSymbols#getInfinity
868N/A * getInfinity()}</td></tr>
869N/A * </table></blockquote>
0N/A *
869N/A * <a name="number-syntax">
869N/A * <h4> Number syntax </h4>
868N/A *
868N/A * <p> The strings that can be parsed as numbers by an instance of this class
868N/A * are specified in terms of the following regular-expression grammar, where
868N/A * Rmax is the highest digit in the radix being used (for example, Rmax is 9
869N/A * in base 10).
869N/A *
869N/A * <p>
869N/A * <table cellspacing=0 cellpadding=0 align=center>
869N/A *
869N/A * <tr><td valign=top align=right><i>NonASCIIDigit</i>&nbsp;&nbsp;::</td>
869N/A * <td valign=top>= A non-ASCII character c for which
869N/A * {@link java.lang.Character#isDigit Character.isDigit}<tt>(c)</tt>
869N/A * returns&nbsp;true</td></tr>
869N/A *
869N/A * <tr><td>&nbsp;</td></tr>
869N/A *
869N/A * <tr><td align=right><i>Non0Digit</i>&nbsp;&nbsp;::</td>
869N/A * <td><tt>= [1-</tt><i>Rmax</i><tt>] | </tt><i>NonASCIIDigit</i></td></tr>
869N/A *
869N/A * <tr><td>&nbsp;</td></tr>
869N/A *
869N/A * <tr><td align=right><i>Digit</i>&nbsp;&nbsp;::</td>
869N/A * <td><tt>= [0-</tt><i>Rmax</i><tt>] | </tt><i>NonASCIIDigit</i></td></tr>
869N/A *
869N/A * <tr><td>&nbsp;</td></tr>
869N/A *
869N/A * <tr><td valign=top align=right><i>GroupedNumeral</i>&nbsp;&nbsp;::</td>
869N/A * <td valign=top>
869N/A * <table cellpadding=0 cellspacing=0>
869N/A * <tr><td><tt>= (&nbsp;</tt></td>
869N/A * <td><i>Non0Digit</i><tt>
869N/A * </tt><i>Digit</i><tt>?
869N/A * </tt><i>Digit</i><tt>?</tt></td></tr>
869N/A * <tr><td></td>
869N/A * <td><tt>(&nbsp;</tt><i>LocalGroupSeparator</i><tt>
869N/A * </tt><i>Digit</i><tt>
869N/A * </tt><i>Digit</i><tt>
869N/A * </tt><i>Digit</i><tt> )+ )</tt></td></tr>
869N/A * </table></td></tr>
869N/A *
869N/A * <tr><td>&nbsp;</td></tr>
869N/A *
869N/A * <tr><td align=right><i>Numeral</i>&nbsp;&nbsp;::</td>
869N/A * <td><tt>= ( ( </tt><i>Digit</i><tt>+ )
869N/A * | </tt><i>GroupedNumeral</i><tt> )</tt></td></tr>
869N/A *
869N/A * <tr><td>&nbsp;</td></tr>
869N/A *
869N/A * <tr><td valign=top align=right>
869N/A * <a name="Integer-regex"><i>Integer</i>&nbsp;&nbsp;::</td>
869N/A * <td valign=top><tt>= ( [-+]? ( </tt><i>Numeral</i><tt>
869N/A * ) )</tt></td></tr>
869N/A * <tr><td></td>
869N/A * <td><tt>| </tt><i>LocalPositivePrefix</i><tt> </tt><i>Numeral</i><tt>
869N/A * </tt><i>LocalPositiveSuffix</i></td></tr>
869N/A * <tr><td></td>
869N/A * <td><tt>| </tt><i>LocalNegativePrefix</i><tt> </tt><i>Numeral</i><tt>
869N/A * </tt><i>LocalNegativeSuffix</i></td></tr>
869N/A *
869N/A * <tr><td>&nbsp;</td></tr>
869N/A *
869N/A * <tr><td align=right><i>DecimalNumeral</i>&nbsp;&nbsp;::</td>
869N/A * <td><tt>= </tt><i>Numeral</i></td></tr>
869N/A * <tr><td></td>
869N/A * <td><tt>| </tt><i>Numeral</i><tt>
869N/A * </tt><i>LocalDecimalSeparator</i><tt>
869N/A * </tt><i>Digit</i><tt>*</tt></td></tr>
0N/A * <tr><td></td>
824N/A * <td><tt>| </tt><i>LocalDecimalSeparator</i><tt>
869N/A * </tt><i>Digit</i><tt>+</tt></td></tr>
868N/A *
824N/A * <tr><td>&nbsp;</td></tr>
824N/A *
824N/A * <tr><td align=right><i>Exponent</i>&nbsp;&nbsp;::</td>
824N/A * <td><tt>= ( [eE] [+-]? </tt><i>Digit</i><tt>+ )</tt></td></tr>
824N/A *
869N/A * <tr><td>&nbsp;</td></tr>
824N/A *
824N/A * <tr><td align=right>
869N/A * <a name="Decimal-regex"><i>Decimal</i>&nbsp;&nbsp;::</td>
869N/A * <td><tt>= ( [-+]? </tt><i>DecimalNumeral</i><tt>
869N/A * </tt><i>Exponent</i><tt>? )</tt></td></tr>
869N/A * <tr><td></td>
869N/A * <td><tt>| </tt><i>LocalPositivePrefix</i><tt>
869N/A * </tt><i>DecimalNumeral</i><tt>
869N/A * </tt><i>LocalPositiveSuffix</i>
869N/A * </tt><i>Exponent</i><tt>?</td></tr>
869N/A * <tr><td></td>
869N/A * <td><tt>| </tt><i>LocalNegativePrefix</i><tt>
869N/A * </tt><i>DecimalNumeral</i><tt>
869N/A * </tt><i>LocalNegativeSuffix</i>
869N/A * </tt><i>Exponent</i><tt>?</td></tr>
869N/A *
869N/A * <tr><td>&nbsp;</td></tr>
869N/A *
869N/A * <tr><td align=right><i>HexFloat</i>&nbsp;&nbsp;::</td>
869N/A * <td><tt>= [-+]? 0[xX][0-9a-fA-F]*\.[0-9a-fA-F]+
869N/A * ([pP][-+]?[0-9]+)?</tt></td></tr>
869N/A *
869N/A * <tr><td>&nbsp;</td></tr>
869N/A *
869N/A * <tr><td align=right><i>NonNumber</i>&nbsp;&nbsp;::</td>
869N/A * <td valign=top><tt>= NaN
869N/A * | </tt><i>LocalNan</i><tt>
869N/A * | Infinity
869N/A * | </tt><i>LocalInfinity</i></td></tr>
869N/A *
869N/A * <tr><td>&nbsp;</td></tr>
849N/A *
0N/A * <tr><td align=right><i>SignedNonNumber</i>&nbsp;&nbsp;::</td>
869N/A * <td><tt>= ( [-+]? </tt><i>NonNumber</i><tt> )</tt></td></tr>
868N/A * <tr><td></td>
0N/A * <td><tt>| </tt><i>LocalPositivePrefix</i><tt>
0N/A * </tt><i>NonNumber</i><tt>
0N/A * </tt><i>LocalPositiveSuffix</i></td></tr>
0N/A * <tr><td></td>
0N/A * <td><tt>| </tt><i>LocalNegativePrefix</i><tt>
0N/A * </tt><i>NonNumber</i><tt>
869N/A * </tt><i>LocalNegativeSuffix</i></td></tr>
869N/A *
869N/A * <tr><td>&nbsp;</td></tr>
869N/A *
869N/A * <tr><td valign=top align=right>
869N/A * <a name="Float-regex"><i>Float</i>&nbsp;&nbsp;::</td>
869N/A * <td valign=top><tt>= </tt><i>Decimal</i><tt></td></tr>
869N/A * <tr><td></td>
0N/A * <td><tt>| </tt><i>HexFloat</i><tt></td></tr>
869N/A * <tr><td></td>
0N/A * <td><tt>| </tt><i>SignedNonNumber</i><tt></td></tr>
0N/A *
869N/A * </table>
869N/A * </center>
869N/A *
869N/A * <p> Whitespace is not significant in the above regular expressions.
869N/A *
868N/A * @since 1.5
0N/A */
824N/Apublic final class Scanner implements Iterator<String> {
824N/A
824N/A // Internal buffer used to hold input
824N/A private CharBuffer buf;
869N/A
869N/A // Size of internal character buffer
869N/A private static final int BUFFER_SIZE = 1024; // change to 1024;
869N/A
869N/A // The index into the buffer currently held by the Scanner
869N/A private int position;
869N/A
869N/A // Internal matcher used for finding delimiters
869N/A private Matcher matcher;
868N/A
824N/A // Pattern used to delimit tokens
868N/A private Pattern delimPattern;
869N/A
869N/A // Pattern found in last hasNext operation
868N/A private Pattern hasNextPattern;
869N/A
869N/A // Position after last hasNext operation
824N/A private int hasNextPosition;
824N/A
869N/A // Result after last hasNext operation
869N/A private String hasNextResult;
869N/A
869N/A // The input source
869N/A private Readable source;
869N/A
869N/A // Boolean is true if source is done
869N/A private boolean sourceClosed = false;
0N/A
869N/A // Boolean indicating more input is required
869N/A private boolean needInput = false;
869N/A
0N/A // Boolean indicating if a delim has been skipped this operation
0N/A private boolean skipped = false;
869N/A
0N/A // A store of a position that the scanner may fall back to
869N/A private int savedScannerPosition = -1;
869N/A
0N/A // A cache of the last primitive type scanned
0N/A private Object typeCache = null;
0N/A
0N/A // Boolean indicating if a match result is available
869N/A private boolean matchValid = false;
868N/A
0N/A // Boolean indicating if this scanner has been closed
0N/A private boolean closed = false;
0N/A
0N/A // The current radix used by this scanner
0N/A private int radix = 10;
869N/A
0N/A // The default radix for this scanner
0N/A private int defaultRadix = 10;
0N/A
0N/A // The locale used by this scanner
0N/A private Locale locale = null;
0N/A
46N/A // A cache of the last few recently used Patterns
869N/A private LRUCache<String,Pattern> patternCache =
0N/A new LRUCache<String,Pattern>(7) {
0N/A protected Pattern create(String s) {
46N/A return Pattern.compile(s);
0N/A }
0N/A protected boolean hasName(Pattern p, String s) {
0N/A return p.pattern().equals(s);
0N/A }
869N/A };
0N/A
0N/A // A holder of the last IOException encountered
0N/A private IOException lastException;
0N/A
0N/A // A pattern for java whitespace
0N/A private static Pattern WHITESPACE_PATTERN = Pattern.compile(
869N/A "\\p{javaWhitespace}+");
0N/A
0N/A // A pattern for any token
0N/A private static Pattern FIND_ANY_PATTERN = Pattern.compile("(?s).*");
756N/A
869N/A // A pattern for non-ASCII digits
868N/A private static Pattern NON_ASCII_DIGIT = Pattern.compile(
756N/A "[\\p{javaDigit}&&[^0-9]]");
756N/A
988N/A // Fields and methods to support scanning primitive types
988N/A
988N/A /**
988N/A * Locale dependent values used to scan numbers
988N/A */
988N/A private String groupSeparator = "\\,";
988N/A private String decimalSeparator = "\\.";
756N/A private String nanString = "NaN";
756N/A private String infinityString = "Infinity";
756N/A private String positivePrefix = "";
869N/A private String negativePrefix = "\\-";
756N/A private String positiveSuffix = "";
869N/A private String negativeSuffix = "";
756N/A
0N/A /**
869N/A * Fields and an accessor method to match booleans
868N/A */
0N/A private static volatile Pattern boolPattern;
0N/A private static final String BOOLEAN_PATTERN = "true|false";
0N/A private static Pattern boolPattern() {
0N/A Pattern bp = boolPattern;
0N/A if (bp == null)
869N/A boolPattern = bp = Pattern.compile(BOOLEAN_PATTERN,
869N/A Pattern.CASE_INSENSITIVE);
0N/A return bp;
0N/A }
0N/A
0N/A /**
824N/A * Fields and methods to match bytes, shorts, ints, and longs
869N/A */
868N/A private Pattern integerPattern;
824N/A private String digits = "0123456789abcdefghijklmnopqrstuvwxyz";
824N/A private String non0Digit = "[\\p{javaDigit}&&[^0]]";
824N/A private int SIMPLE_GROUP_INDEX = 5;
869N/A private String buildIntegerPatternString() {
868N/A String radixDigits = digits.substring(0, radix);
824N/A // \\p{javaDigit} is not guaranteed to be appropriate
869N/A // here but what can we do? The final authority will be
824N/A // whatever parse method is invoked, so ultimately the
869N/A // Scanner will do the right thing
869N/A String digit = "((?i)["+radixDigits+"]|\\p{javaDigit})";
869N/A String groupedNumeral = "("+non0Digit+digit+"?"+digit+"?("+
869N/A groupSeparator+digit+digit+digit+")+)";
869N/A // digit++ is the possessive form which is necessary for reducing
869N/A // backtracking that would otherwise cause unacceptable performance
869N/A String numeral = "(("+ digit+"++)|"+groupedNumeral+")";
869N/A String javaStyleInteger = "([-+]?(" + numeral + "))";
869N/A String negativeInteger = negativePrefix + numeral + negativeSuffix;
869N/A String positiveInteger = positivePrefix + numeral + positiveSuffix;
869N/A return "("+ javaStyleInteger + ")|(" +
869N/A positiveInteger + ")|(" +
869N/A negativeInteger + ")";
869N/A }
869N/A private Pattern integerPattern() {
868N/A if (integerPattern == null) {
868N/A integerPattern = patternCache.forName(buildIntegerPatternString());
869N/A }
868N/A return integerPattern;
868N/A }
869N/A
868N/A /**
824N/A * Fields and an accessor method to match line separators
869N/A */
824N/A private static volatile Pattern separatorPattern;
0N/A private static volatile Pattern linePattern;
869N/A private static final String LINE_SEPARATOR_PATTERN =
868N/A "\r\n|[\n\r\u2028\u2029\u0085]";
0N/A private static final String LINE_PATTERN = ".*("+LINE_SEPARATOR_PATTERN+")|.+$";
0N/A
0N/A private static Pattern separatorPattern() {
869N/A Pattern sp = separatorPattern;
868N/A if (sp == null)
0N/A separatorPattern = sp = Pattern.compile(LINE_SEPARATOR_PATTERN);
869N/A return sp;
869N/A }
868N/A
868N/A private static Pattern linePattern() {
869N/A Pattern lp = linePattern;
869N/A if (lp == null)
0N/A linePattern = lp = Pattern.compile(LINE_PATTERN);
0N/A return lp;
869N/A }
869N/A
869N/A /**
869N/A * Fields and methods to match floats and doubles
869N/A */
869N/A private Pattern floatPattern;
869N/A private Pattern decimalPattern;
869N/A private void buildFloatAndDecimalPattern() {
869N/A // \\p{javaDigit} may not be perfect, see above
868N/A String digit = "([0-9]|(\\p{javaDigit}))";
869N/A String exponent = "([eE][+-]?"+digit+"+)?";
869N/A String groupedNumeral = "("+non0Digit+digit+"?"+digit+"?("+
868N/A groupSeparator+digit+digit+digit+")+)";
869N/A // Once again digit++ is used for performance, as above
869N/A String numeral = "(("+digit+"++)|"+groupedNumeral+")";
0N/A String decimalNumeral = "("+numeral+"|"+numeral +
869N/A decimalSeparator + digit + "*+|"+ decimalSeparator +
0N/A digit + "++)";
0N/A String nonNumber = "(NaN|"+nanString+"|Infinity|"+
869N/A infinityString+")";
868N/A String positiveFloat = "(" + positivePrefix + decimalNumeral +
868N/A positiveSuffix + exponent + ")";
869N/A String negativeFloat = "(" + negativePrefix + decimalNumeral +
869N/A negativeSuffix + exponent + ")";
869N/A String decimal = "(([-+]?" + decimalNumeral + exponent + ")|"+
869N/A positiveFloat + "|" + negativeFloat + ")";
868N/A String hexFloat =
0N/A "[-+]?0[xX][0-9a-fA-F]*\\.[0-9a-fA-F]+([pP][-+]?[0-9]+)?";
0N/A String positiveNonNumber = "(" + positivePrefix + nonNumber +
0N/A positiveSuffix + ")";
0N/A String negativeNonNumber = "(" + negativePrefix + nonNumber +
869N/A negativeSuffix + ")";
0N/A String signedNonNumber = "(([-+]?"+nonNumber+")|" +
0N/A positiveNonNumber + "|" +
0N/A negativeNonNumber + ")";
869N/A floatPattern = Pattern.compile(decimal + "|" + hexFloat + "|" +
869N/A signedNonNumber);
869N/A decimalPattern = Pattern.compile(decimal);
868N/A }
0N/A private Pattern floatPattern() {
0N/A if (floatPattern == null) {
0N/A buildFloatAndDecimalPattern();
0N/A }
869N/A return floatPattern;
869N/A }
0N/A private Pattern decimalPattern() {
869N/A if (decimalPattern == null) {
0N/A buildFloatAndDecimalPattern();
0N/A }
869N/A return decimalPattern;
868N/A }
0N/A
0N/A // Constructors
0N/A
0N/A /**
0N/A * Constructs a <code>Scanner</code> that returns values scanned
869N/A * from the specified source delimited by the specified pattern.
868N/A *
868N/A * @param source A character source implementing the Readable interface
869N/A * @param pattern A delimiting pattern
868N/A * @return A scanner with the specified source and pattern
868N/A */
868N/A private Scanner(Readable source, Pattern pattern) {
868N/A if (source == null)
869N/A throw new NullPointerException("source");
0N/A if (pattern == null)
0N/A throw new NullPointerException("pattern");
869N/A this.source = source;
0N/A delimPattern = pattern;
0N/A buf = CharBuffer.allocate(BUFFER_SIZE);
0N/A buf.limit(0);
0N/A matcher = delimPattern.matcher(buf);
869N/A matcher.useTransparentBounds(true);
0N/A matcher.useAnchoringBounds(false);
0N/A useLocale(Locale.getDefault());
869N/A }
0N/A
0N/A /**
0N/A * Constructs a new <code>Scanner</code> that produces values scanned
0N/A * from the specified source.
869N/A *
0N/A * @param source A character source implementing the {@link Readable}
0N/A * interface
869N/A */
0N/A public Scanner(Readable source) {
0N/A this(source, WHITESPACE_PATTERN);
868N/A }
868N/A
869N/A /**
869N/A * Constructs a new <code>Scanner</code> that produces values scanned
869N/A * from the specified input stream. Bytes from the stream are converted
0N/A * into characters using the underlying platform's
868N/A * {@linkplain java.nio.charset.Charset#defaultCharset() default charset}.
869N/A *
868N/A * @param source An input stream to be scanned
868N/A */
868N/A public Scanner(InputStream source) {
0N/A this(new InputStreamReader(source), WHITESPACE_PATTERN);
0N/A }
869N/A
0N/A /**
0N/A * Constructs a new <code>Scanner</code> that produces values scanned
0N/A * from the specified input stream. Bytes from the stream are converted
0N/A * into characters using the specified charset.
0N/A *
0N/A * @param source An input stream to be scanned
0N/A * @param charsetName The encoding type used to convert bytes from the
869N/A * stream into characters to be scanned
869N/A * @throws IllegalArgumentException if the specified character set
869N/A * does not exist
869N/A */
869N/A public Scanner(InputStream source, String charsetName) {
869N/A this(makeReadable(source, charsetName), WHITESPACE_PATTERN);
869N/A }
869N/A
869N/A private static Readable makeReadable(InputStream source,
869N/A String charsetName)
869N/A {
869N/A if (source == null)
869N/A throw new NullPointerException("source");
869N/A InputStreamReader isr = null;
869N/A try {
869N/A isr = new InputStreamReader(source, charsetName);
869N/A } catch (UnsupportedEncodingException uee) {
0N/A IllegalArgumentException iae = new IllegalArgumentException();
868N/A iae.initCause(uee);
0N/A throw iae;
0N/A }
869N/A return isr;
0N/A }
0N/A
869N/A /**
869N/A * Constructs a new <code>Scanner</code> that produces values scanned
869N/A * from the specified file. Bytes from the file are converted into
869N/A * characters using the underlying platform's
869N/A * {@linkplain java.nio.charset.Charset#defaultCharset() default charset}.
869N/A *
869N/A * @param source A file to be scanned
869N/A * @throws FileNotFoundException if source is not found
869N/A */
869N/A public Scanner(File source)
869N/A throws FileNotFoundException
869N/A {
869N/A this((ReadableByteChannel)(new FileInputStream(source).getChannel()));
869N/A }
869N/A
869N/A /**
869N/A * Constructs a new <code>Scanner</code> that produces values scanned
0N/A * from the specified file. Bytes from the file are converted into
868N/A * characters using the specified charset.
0N/A *
0N/A * @param source A file to be scanned
869N/A * @param charsetName The encoding type used to convert bytes from the file
0N/A * into characters to be scanned
0N/A * @throws FileNotFoundException if source is not found
869N/A * @throws IllegalArgumentException if the specified encoding is
0N/A * not found
0N/A */
0N/A public Scanner(File source, String charsetName)
0N/A throws FileNotFoundException
0N/A {
0N/A this((ReadableByteChannel)(new FileInputStream(source).getChannel()),
0N/A charsetName);
869N/A }
0N/A
0N/A /**
0N/A * {@note new}
0N/A * Constructs a new <code>Scanner</code> that produces values scanned
869N/A * from the specified file. Bytes from the file are converted into
0N/A * characters using the underlying platform's
0N/A * {@linkplain java.nio.charset.Charset#defaultCharset() default charset}.
869N/A *
0N/A * @param source
0N/A * A file to be scanned
0N/A * @throws IOException
0N/A * if an I/O error occurs opening source
0N/A *
0N/A * @since 1.7
0N/A */
869N/A public Scanner(FileRef source)
868N/A throws IOException
869N/A {
868N/A this(source.newByteChannel());
868N/A }
869N/A
869N/A /**
869N/A * {@note new}
868N/A * Constructs a new <code>Scanner</code> that produces values scanned
0N/A * from the specified file. Bytes from the file are converted into
869N/A * characters using the specified charset.
0N/A *
0N/A * @param source
868N/A * A file to be scanned
0N/A * @param charsetName
0N/A * The encoding type used to convert bytes from the file
869N/A * into characters to be scanned
0N/A * @throws IOException
0N/A * if an I/O error occurs opening source
0N/A * @throws IllegalArgumentException
0N/A * if the specified encoding is not found
0N/A * @since 1.7
0N/A */
0N/A public Scanner(FileRef source, String charsetName)
869N/A throws IOException
0N/A {
0N/A this(source.newByteChannel(), charsetName);
0N/A }
0N/A
869N/A /**
0N/A * Constructs a new <code>Scanner</code> that produces values scanned
0N/A * from the specified string.
869N/A *
0N/A * @param source A string to scan
0N/A */
0N/A public Scanner(String source) {
0N/A this(new StringReader(source), WHITESPACE_PATTERN);
869N/A }
0N/A
0N/A /**
869N/A * Constructs a new <code>Scanner</code> that produces values scanned
0N/A * from the specified channel. Bytes from the source are converted into
0N/A * characters using the underlying platform's
0N/A * {@linkplain java.nio.charset.Charset#defaultCharset() default charset}.
0N/A *
0N/A * @param source A channel to scan
869N/A */
0N/A public Scanner(ReadableByteChannel source) {
0N/A this(makeReadable(source), WHITESPACE_PATTERN);
0N/A }
0N/A
0N/A private static Readable makeReadable(ReadableByteChannel source) {
0N/A if (source == null)
869N/A throw new NullPointerException("source");
0N/A String defaultCharsetName =
0N/A java.nio.charset.Charset.defaultCharset().name();
869N/A return Channels.newReader(source,
0N/A java.nio.charset.Charset.defaultCharset().name());
869N/A }
0N/A
0N/A /**
869N/A * Constructs a new <code>Scanner</code> that produces values scanned
869N/A * from the specified channel. Bytes from the source are converted into
869N/A * characters using the specified charset.
0N/A *
0N/A * @param source A channel to scan
869N/A * @param charsetName The encoding type used to convert bytes from the
0N/A * channel into characters to be scanned
0N/A * @throws IllegalArgumentException if the specified character set
869N/A * does not exist
869N/A */
869N/A public Scanner(ReadableByteChannel source, String charsetName) {
868N/A this(makeReadable(source, charsetName), WHITESPACE_PATTERN);
868N/A }
868N/A
0N/A private static Readable makeReadable(ReadableByteChannel source,
0N/A String charsetName)
869N/A {
868N/A if (source == null)
868N/A throw new NullPointerException("source");
869N/A if (!Charset.isSupported(charsetName))
868N/A throw new IllegalArgumentException(charsetName);
868N/A return Channels.newReader(source, charsetName);
868N/A }
868N/A
869N/A // Private primitives used to support scanning
0N/A
0N/A private void saveState() {
869N/A savedScannerPosition = position;
0N/A }
0N/A
0N/A private void revertState() {
0N/A this.position = savedScannerPosition;
869N/A savedScannerPosition = -1;
0N/A skipped = false;
0N/A }
869N/A
0N/A private boolean revertState(boolean b) {
0N/A this.position = savedScannerPosition;
0N/A savedScannerPosition = -1;
0N/A skipped = false;
0N/A return b;
0N/A }
0N/A
869N/A private void cacheResult() {
0N/A hasNextResult = matcher.group();
0N/A hasNextPosition = matcher.end();
0N/A hasNextPattern = matcher.pattern();
0N/A }
869N/A
0N/A private void cacheResult(String result) {
0N/A hasNextResult = result;
869N/A hasNextPosition = matcher.end();
0N/A hasNextPattern = matcher.pattern();
0N/A }
0N/A
0N/A // Clears both regular cache and type cache
869N/A private void clearCaches() {
0N/A hasNextPattern = null;
0N/A typeCache = null;
869N/A }
0N/A
0N/A // Also clears both the regular cache and the type cache
0N/A private String getCachedResult() {
0N/A position = hasNextPosition;
869N/A hasNextPattern = null;
0N/A typeCache = null;
0N/A return hasNextResult;
869N/A }
0N/A
0N/A // Also clears both the regular cache and the type cache
0N/A private void useTypeCache() {
0N/A if (closed)
869N/A throw new IllegalStateException("Scanner closed");
0N/A position = hasNextPosition;
0N/A hasNextPattern = null;
869N/A typeCache = null;
0N/A }
0N/A
0N/A // Tries to read more input. May block.
0N/A private void readInput() {
0N/A if (buf.limit() == buf.capacity())
0N/A makeSpace();
0N/A
869N/A // Prepare to receive data
0N/A int p = buf.position();
0N/A buf.position(buf.limit());
0N/A buf.limit(buf.capacity());
0N/A
869N/A int n = 0;
0N/A try {
0N/A n = source.read(buf);
869N/A } catch (IOException ioe) {
0N/A lastException = ioe;
0N/A n = -1;
0N/A }
0N/A
869N/A if (n == -1) {
0N/A sourceClosed = true;
0N/A needInput = false;
869N/A }
0N/A
0N/A if (n > 0)
0N/A needInput = false;
0N/A
869N/A // Restore current position and limit for reading
0N/A buf.limit(buf.position());
0N/A buf.position(p);
869N/A }
0N/A
0N/A // After this method is called there will either be an exception
0N/A // or else there will be space in the buffer
0N/A private boolean makeSpace() {
0N/A clearCaches();
0N/A int offset = savedScannerPosition == -1 ?
0N/A position : savedScannerPosition;
869N/A buf.position(offset);
0N/A // Gain space by compacting buffer
0N/A if (offset > 0) {
0N/A buf.compact();
0N/A translateSavedIndexes(offset);
869N/A position -= offset;
0N/A buf.flip();
0N/A return true;
869N/A }
0N/A // Gain space by growing buffer
0N/A int newSize = buf.capacity() * 2;
0N/A CharBuffer newBuf = CharBuffer.allocate(newSize);
0N/A newBuf.put(buf);
869N/A newBuf.flip();
0N/A translateSavedIndexes(offset);
0N/A position -= offset;
869N/A buf = newBuf;
0N/A matcher.reset(buf);
0N/A return true;
0N/A }
0N/A
869N/A // When a buffer compaction/reallocation occurs the saved indexes must
0N/A // be modified appropriately
0N/A private void translateSavedIndexes(int offset) {
869N/A if (savedScannerPosition != -1)
0N/A savedScannerPosition -= offset;
0N/A }
0N/A
0N/A // If we are at the end of input then NoSuchElement;
869N/A // If there is still input left then InputMismatch
0N/A private void throwFor() {
0N/A skipped = false;
869N/A if ((sourceClosed) && (position == buf.limit()))
0N/A throw new NoSuchElementException();
0N/A else
0N/A throw new InputMismatchException();
0N/A }
869N/A
0N/A // Returns true if a complete token or partial token is in the buffer.
0N/A // It is not necessary to find a complete token since a partial token
869N/A // means that there will be another token with or without more input.
0N/A private boolean hasTokenInBuffer() {
0N/A matchValid = false;
0N/A matcher.usePattern(delimPattern);
0N/A matcher.region(position, buf.limit());
0N/A
0N/A // Skip delims first
0N/A if (matcher.lookingAt())
869N/A position = matcher.end();
0N/A
0N/A // If we are sitting at the end, no more tokens in buffer
869N/A if (position == buf.limit())
868N/A return false;
0N/A
0N/A return true;
0N/A }
869N/A
868N/A /*
869N/A * Returns a "complete token" that matches the specified pattern
0N/A *
0N/A * A token is complete if surrounded by delims; a partial token
0N/A * is prefixed by delims but not postfixed by them
0N/A *
869N/A * The position is advanced to the end of that complete token
868N/A *
869N/A * Pattern == null means accept any token at all
0N/A *
0N/A * Triple return:
0N/A * 1. valid string means it was found
0N/A * 2. null with needInput=false means we won't ever find it
869N/A * 3. null with needInput=true means try again after readInput
868N/A */
869N/A private String getCompleteTokenInBuffer(Pattern pattern) {
0N/A matchValid = false;
0N/A
0N/A // Skip delims first
0N/A matcher.usePattern(delimPattern);
869N/A if (!skipped) { // Enforcing only one skip of leading delims
868N/A matcher.region(position, buf.limit());
0N/A if (matcher.lookingAt()) {
0N/A // If more input could extend the delimiters then we must wait
0N/A // for more input
869N/A if (matcher.hitEnd() && !sourceClosed) {
868N/A needInput = true;
0N/A return null;
869N/A }
0N/A // The delims were whole and the matcher should skip them
869N/A skipped = true;
0N/A position = matcher.end();
0N/A }
869N/A }
0N/A
0N/A // If we are sitting at the end, no more tokens in buffer
869N/A if (position == buf.limit()) {
868N/A if (sourceClosed)
0N/A return null;
0N/A needInput = true;
869N/A return null;
868N/A }
869N/A
869N/A // Must look for next delims. Simply attempting to match the
869N/A // pattern at this point may find a match but it might not be
869N/A // the first longest match because of missing input, or it might
869N/A // match a partial token instead of the whole thing.
868N/A
869N/A // Then look for next delims
869N/A matcher.region(position, buf.limit());
869N/A boolean foundNextDelim = matcher.find();
868N/A if (foundNextDelim && (matcher.end() == position)) {
868N/A // Zero length delimiter match; we should find the next one
868N/A // using the automatic advance past a zero length match;
868N/A // Otherwise we have just found the same one we just skipped
869N/A foundNextDelim = matcher.find();
0N/A }
869N/A if (foundNextDelim) {
869N/A // In the rare case that more input could cause the match
0N/A // to be lost and there is more input coming we must wait
0N/A // for more input. Note that hitting the end is okay as long
869N/A // as the match cannot go away. It is the beginning of the
0N/A // next delims we want to be sure about, we don't care if
869N/A // they potentially extend further.
868N/A if (matcher.requireEnd() && !sourceClosed) {
868N/A needInput = true;
869N/A return null;
0N/A }
245N/A int tokenEnd = matcher.start();
869N/A // There is a complete token.
868N/A if (pattern == null) {
869N/A // Must continue with match to provide valid MatchResult
869N/A pattern = FIND_ANY_PATTERN;
549N/A }
869N/A // Attempt to match against the desired pattern
245N/A matcher.usePattern(pattern);
869N/A matcher.region(position, tokenEnd);
245N/A if (matcher.matches()) {
245N/A String s = matcher.group();
868N/A position = matcher.end();
869N/A return s;
869N/A } else { // Complete token but it does not match
869N/A return null;
245N/A }
245N/A }
869N/A
869N/A // If we can't find the next delims but no more input is coming,
245N/A // then we can treat the remainder as a whole token
245N/A if (sourceClosed) {
869N/A if (pattern == null) {
869N/A // Must continue with match to provide valid MatchResult
245N/A pattern = FIND_ANY_PATTERN;
245N/A }
245N/A // Last token; Match the pattern here or throw
245N/A matcher.usePattern(pattern);
0N/A matcher.region(position, buf.limit());
869N/A if (matcher.matches()) {
868N/A String s = matcher.group();
0N/A position = matcher.end();
0N/A return s;
0N/A }
0N/A // Last piece does not match
0N/A return null;
869N/A }
0N/A
869N/A // There is a partial token in the buffer; must read more
0N/A // to complete it
0N/A needInput = true;
0N/A return null;
0N/A }
869N/A
0N/A // Finds the specified pattern in the buffer up to horizon.
869N/A // Returns a match for the specified input pattern.
0N/A private String findPatternInBuffer(Pattern pattern, int horizon) {
0N/A matchValid = false;
0N/A matcher.usePattern(pattern);
0N/A int bufferLimit = buf.limit();
869N/A int horizonLimit = -1;
0N/A int searchLimit = bufferLimit;
869N/A if (horizon > 0) {
0N/A horizonLimit = position + horizon;
0N/A if (horizonLimit < bufferLimit)
0N/A searchLimit = horizonLimit;
0N/A }
869N/A matcher.region(position, searchLimit);
0N/A if (matcher.find()) {
869N/A if (matcher.hitEnd() && (!sourceClosed)) {
0N/A // The match may be longer if didn't hit horizon or real end
0N/A if (searchLimit != horizonLimit) {
0N/A // Hit an artificial end; try to extend the match
0N/A needInput = true;
869N/A return null;
0N/A }
869N/A // The match could go away depending on what is next
0N/A if ((searchLimit == horizonLimit) && matcher.requireEnd()) {
0N/A // Rare case: we hit the end of input and it happens
0N/A // that it is at the horizon and the end of input is
0N/A // required for the match.
869N/A needInput = true;
0N/A return null;
869N/A }
0N/A }
0N/A // Did not hit end, or hit real end, or hit horizon
0N/A position = matcher.end();
0N/A return matcher.group();
869N/A }
0N/A
869N/A if (sourceClosed)
0N/A return null;
0N/A
0N/A // If there is no specified horizon, or if we have not searched
0N/A // to the specified horizon yet, get more input
869N/A if ((horizon == 0) || (searchLimit != horizonLimit))
0N/A needInput = true;
869N/A return null;
0N/A }
0N/A
0N/A // Returns a match for the specified input pattern anchored at
0N/A // the current position
869N/A private String matchPatternInBuffer(Pattern pattern) {
0N/A matchValid = false;
869N/A matcher.usePattern(pattern);
0N/A matcher.region(position, buf.limit());
0N/A if (matcher.lookingAt()) {
869N/A if (matcher.hitEnd() && (!sourceClosed)) {
868N/A // Get more input and try again
0N/A needInput = true;
0N/A return null;
0N/A }
869N/A position = matcher.end();
868N/A return matcher.group();
0N/A }
869N/A
868N/A if (sourceClosed)
0N/A return null;
869N/A
869N/A // Read more to find pattern
0N/A needInput = true;
1026N/A return null;
1026N/A }
1026N/A
1026N/A // Throws if the scanner is closed
1026N/A private void ensureOpen() {
1026N/A if (closed)
1026N/A throw new IllegalStateException("Scanner closed");
1026N/A }
1026N/A
1026N/A // Public methods
1017N/A
1017N/A /**
1017N/A * Closes this scanner.
1017N/A *
1017N/A * <p> If this scanner has not yet been closed then if its underlying
1017N/A * {@linkplain java.lang.Readable readable} also implements the {@link
1017N/A * java.io.Closeable} interface then the readable's <tt>close</tt> method
1017N/A * will be invoked. If this scanner is already closed then invoking this
1017N/A * method will have no effect.
1026N/A *
1026N/A * <p>Attempting to perform search operations after a scanner has
1026N/A * been closed will result in an {@link IllegalStateException}.
1026N/A *
1026N/A */
1026N/A public void close() {
1026N/A if (closed)
1026N/A return;
1026N/A if (source instanceof Closeable) {
1026N/A try {
0N/A ((Closeable)source).close();
869N/A } catch (IOException ioe) {
868N/A lastException = ioe;
0N/A }
0N/A }
0N/A sourceClosed = true;
0N/A source = null;
0N/A closed = true;
869N/A }
0N/A
0N/A /**
0N/A * Returns the <code>IOException</code> last thrown by this
0N/A * <code>Scanner</code>'s underlying <code>Readable</code>. This method
0N/A * returns <code>null</code> if no such exception exists.
0N/A *
0N/A * @return the last exception thrown by this scanner's readable
0N/A */
869N/A public IOException ioException() {
0N/A return lastException;
0N/A }
0N/A
0N/A /**
0N/A * Returns the <code>Pattern</code> this <code>Scanner</code> is currently
0N/A * using to match delimiters.
0N/A *
0N/A * @return this scanner's delimiting pattern.
0N/A */
869N/A public Pattern delimiter() {
0N/A return delimPattern;
0N/A }
0N/A
0N/A /**
0N/A * Sets this scanner's delimiting pattern to the specified pattern.
0N/A *
0N/A * @param pattern A delimiting pattern
869N/A * @return this scanner
0N/A */
0N/A public Scanner useDelimiter(Pattern pattern) {
0N/A delimPattern = pattern;
0N/A return this;
0N/A }
0N/A
869N/A /**
868N/A * Sets this scanner's delimiting pattern to a pattern constructed from
869N/A * the specified <code>String</code>.
869N/A *
868N/A * <p> An invocation of this method of the form
0N/A * <tt>useDelimiter(pattern)</tt> behaves in exactly the same way as the
0N/A * invocation <tt>useDelimiter(Pattern.compile(pattern))</tt>.
869N/A *
869N/A * <p> Invoking the {@link #reset} method will set the scanner's delimiter
0N/A * to the <a href= "#default-delimiter">default</a>.
0N/A *
869N/A * @param pattern A string specifying a delimiting pattern
868N/A * @return this scanner
869N/A */
776N/A public Scanner useDelimiter(String pattern) {
776N/A delimPattern = patternCache.forName(pattern);
776N/A return this;
776N/A }
776N/A
776N/A /**
776N/A * Returns this scanner's locale.
776N/A *
776N/A * <p>A scanner's locale affects many elements of its default
776N/A * primitive matching regular expressions; see
776N/A * <a href= "#localized-numbers">localized numbers</a> above.
776N/A *
776N/A * @return this scanner's locale
776N/A */
776N/A public Locale locale() {
776N/A return this.locale;
0N/A }
0N/A
869N/A /**
868N/A * Sets this scanner's locale to the specified locale.
0N/A *
869N/A * <p>A scanner's locale affects many elements of its default
0N/A * primitive matching regular expressions; see
0N/A * <a href= "#localized-numbers">localized numbers</a> above.
869N/A *
868N/A * <p>Invoking the {@link #reset} method will set the scanner's locale to
869N/A * the <a href= "#initial-locale">initial locale</a>.
0N/A *
869N/A * @param locale A string specifying the locale to use
48N/A * @return this scanner
96N/A */
549N/A public Scanner useLocale(Locale locale) {
0N/A if (locale.equals(this.locale))
869N/A return this;
868N/A
0N/A this.locale = locale;
869N/A DecimalFormat df =
868N/A (DecimalFormat)NumberFormat.getNumberInstance(locale);
0N/A DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(locale);
0N/A
869N/A // These must be literalized to avoid collision with regex
868N/A // metacharacters such as dot or parenthesis
0N/A groupSeparator = "\\" + dfs.getGroupingSeparator();
0N/A decimalSeparator = "\\" + dfs.getDecimalSeparator();
0N/A
869N/A // Quoting the nonzero length locale-specific things
868N/A // to avoid potential conflict with metacharacters
869N/A nanString = "\\Q" + dfs.getNaN() + "\\E";
0N/A infinityString = "\\Q" + dfs.getInfinity() + "\\E";
0N/A positivePrefix = df.getPositivePrefix();
0N/A if (positivePrefix.length() > 0)
0N/A positivePrefix = "\\Q" + positivePrefix + "\\E";
869N/A negativePrefix = df.getNegativePrefix();
868N/A if (negativePrefix.length() > 0)
0N/A negativePrefix = "\\Q" + negativePrefix + "\\E";
869N/A positiveSuffix = df.getPositiveSuffix();
0N/A if (positiveSuffix.length() > 0)
0N/A positiveSuffix = "\\Q" + positiveSuffix + "\\E";
0N/A negativeSuffix = df.getNegativeSuffix();
0N/A if (negativeSuffix.length() > 0)
0N/A negativeSuffix = "\\Q" + negativeSuffix + "\\E";
869N/A
868N/A // Force rebuilding and recompilation of locale dependent
0N/A // primitive patterns
869N/A integerPattern = null;
0N/A floatPattern = null;
0N/A
0N/A return this;
0N/A }
0N/A
869N/A /**
868N/A * Returns this scanner's default radix.
0N/A *
869N/A * <p>A scanner's radix affects elements of its default
869N/A * number matching regular expressions; see
868N/A * <a href= "#localized-numbers">localized numbers</a> above.
869N/A *
869N/A * @return the default radix of this scanner
868N/A */
0N/A public int radix() {
0N/A return this.defaultRadix;
869N/A }
0N/A
0N/A /**
869N/A * Sets this scanner's default radix to the specified radix.
0N/A *
869N/A * <p>A scanner's radix affects elements of its default
869N/A * number matching regular expressions; see
868N/A * <a href= "#localized-numbers">localized numbers</a> above.
0N/A *
0N/A * <p>If the radix is less than <code>Character.MIN_RADIX</code>
869N/A * or greater than <code>Character.MAX_RADIX</code>, then an
0N/A * <code>IllegalArgumentException</code> is thrown.
0N/A *
869N/A * <p>Invoking the {@link #reset} method will set the scanner's radix to
0N/A * <code>10</code>.
0N/A *
0N/A * @param radix The radix to use when scanning numbers
0N/A * @return this scanner
0N/A * @throws IllegalArgumentException if radix is out of range
869N/A */
868N/A public Scanner useRadix(int radix) {
0N/A if ((radix < Character.MIN_RADIX) || (radix > Character.MAX_RADIX))
0N/A throw new IllegalArgumentException("radix:"+radix);
0N/A
869N/A if (this.defaultRadix == radix)
868N/A return this;
0N/A this.defaultRadix = radix;
0N/A // Force rebuilding and recompilation of radix dependent patterns
0N/A integerPattern = null;
0N/A return this;
0N/A }
869N/A
0N/A // The next operation should occur in the specified radix but
0N/A // the default is left untouched.
0N/A private void setRadix(int radix) {
914N/A if (this.radix != radix) {
914N/A // Force rebuilding and recompilation of radix dependent patterns
914N/A integerPattern = null;
914N/A this.radix = radix;
914N/A }
914N/A }
914N/A
0N/A /**
0N/A * Returns the match result of the last scanning operation performed
0N/A * by this scanner. This method throws <code>IllegalStateException</code>
869N/A * if no match has been performed, or if the last match was
0N/A * not successful.
0N/A *
0N/A * <p>The various <code>next</code>methods of <code>Scanner</code>
0N/A * make a match result available if they complete without throwing an
0N/A * exception. For instance, after an invocation of the {@link #nextInt}
0N/A * method that returned an int, this method returns a
869N/A * <code>MatchResult</code> for the search of the
0N/A * <a href="#Integer-regex"><i>Integer</i></a> regular expression
0N/A * defined above. Similarly the {@link #findInLine},
0N/A * {@link #findWithinHorizon}, and {@link #skip} methods will make a
0N/A * match available if they succeed.
0N/A *
0N/A * @return a match result for the last match operation
869N/A * @throws IllegalStateException If no match result is available
0N/A */
0N/A public MatchResult match() {
0N/A if (!matchValid)
0N/A throw new IllegalStateException("No match result available");
0N/A return matcher.toMatchResult();
0N/A }
869N/A
0N/A /**
0N/A * <p>Returns the string representation of this <code>Scanner</code>. The
0N/A * string representation of a <code>Scanner</code> contains information
0N/A * that may be useful for debugging. The exact format is unspecified.
0N/A *
0N/A * @return The string representation of this scanner
869N/A */
0N/A public String toString() {
0N/A StringBuilder sb = new StringBuilder();
0N/A sb.append("java.util.Scanner");
0N/A sb.append("[delimiters=" + delimPattern + "]");
0N/A sb.append("[position=" + position + "]");
0N/A sb.append("[match valid=" + matchValid + "]");
869N/A sb.append("[need input=" + needInput + "]");
0N/A sb.append("[source closed=" + sourceClosed + "]");
0N/A sb.append("[skipped=" + skipped + "]");
0N/A sb.append("[group separator=" + groupSeparator + "]");
0N/A sb.append("[decimal separator=" + decimalSeparator + "]");
0N/A sb.append("[positive prefix=" + positivePrefix + "]");
0N/A sb.append("[negative prefix=" + negativePrefix + "]");
869N/A sb.append("[positive suffix=" + positiveSuffix + "]");
0N/A sb.append("[negative suffix=" + negativeSuffix + "]");
0N/A sb.append("[NaN string=" + nanString + "]");
0N/A sb.append("[infinity string=" + infinityString + "]");
0N/A return sb.toString();
0N/A }
0N/A
869N/A /**
0N/A * Returns true if this scanner has another token in its input.
0N/A * This method may block while waiting for input to scan.
0N/A * The scanner does not advance past any input.
0N/A *
0N/A * @return true if and only if this scanner has another token
0N/A * @throws IllegalStateException if this scanner is closed
869N/A * @see java.util.Iterator
0N/A */
0N/A public boolean hasNext() {
0N/A ensureOpen();
0N/A saveState();
0N/A while (!sourceClosed) {
0N/A if (hasTokenInBuffer())
869N/A return revertState(true);
0N/A readInput();
0N/A }
0N/A boolean result = hasTokenInBuffer();
0N/A return revertState(result);
0N/A }
869N/A
868N/A /**
869N/A * Finds and returns the next complete token from this scanner.
0N/A * A complete token is preceded and followed by input that matches
0N/A * the delimiter pattern. This method may block while waiting for input
869N/A * to scan, even if a previous invocation of {@link #hasNext} returned
0N/A * <code>true</code>.
0N/A *
0N/A * @return the next token
0N/A * @throws NoSuchElementException if no more tokens are available
869N/A * @throws IllegalStateException if this scanner is closed
0N/A * @see java.util.Iterator
0N/A */
0N/A public String next() {
0N/A ensureOpen();
0N/A clearCaches();
0N/A
869N/A while (true) {
0N/A String token = getCompleteTokenInBuffer(null);
0N/A if (token != null) {
0N/A matchValid = true;
0N/A skipped = false;
0N/A return token;
0N/A }
869N/A if (needInput)
0N/A readInput();
0N/A else
0N/A throwFor();
0N/A }
0N/A }
0N/A
869N/A /**
0N/A * The remove operation is not supported by this implementation of
0N/A * <code>Iterator</code>.
0N/A *
0N/A * @throws UnsupportedOperationException if this method is invoked.
0N/A * @see java.util.Iterator
0N/A */
869N/A public void remove() {
0N/A throw new UnsupportedOperationException();
0N/A }
0N/A
0N/A /**
0N/A * Returns true if the next token matches the pattern constructed from the
0N/A * specified string. The scanner does not advance past any input.
869N/A *
0N/A * <p> An invocation of this method of the form <tt>hasNext(pattern)</tt>
0N/A * behaves in exactly the same way as the invocation
0N/A * <tt>hasNext(Pattern.compile(pattern))</tt>.
0N/A *
0N/A * @param pattern a string specifying the pattern to scan
0N/A * @return true if and only if this scanner has another token matching
869N/A * the specified pattern
0N/A * @throws IllegalStateException if this scanner is closed
0N/A */
0N/A public boolean hasNext(String pattern) {
0N/A return hasNext(patternCache.forName(pattern));
0N/A }
0N/A
869N/A /**
0N/A * Returns the next token if it matches the pattern constructed from the
0N/A * specified string. If the match is successful, the scanner advances
0N/A * past the input that matched the pattern.
0N/A *
0N/A * <p> An invocation of this method of the form <tt>next(pattern)</tt>
0N/A * behaves in exactly the same way as the invocation
869N/A * <tt>next(Pattern.compile(pattern))</tt>.
0N/A *
0N/A * @param pattern a string specifying the pattern to scan
0N/A * @return the next token
0N/A * @throws NoSuchElementException if no such tokens are available
0N/A * @throws IllegalStateException if this scanner is closed
0N/A */
869N/A public String next(String pattern) {
0N/A return next(patternCache.forName(pattern));
0N/A }
0N/A
0N/A /**
0N/A * Returns true if the next complete token matches the specified pattern.
0N/A * A complete token is prefixed and postfixed by input that matches
869N/A * the delimiter pattern. This method may block while waiting for input.
0N/A * The scanner does not advance past any input.
0N/A *
0N/A * @param pattern the pattern to scan for
0N/A * @return true if and only if this scanner has another token matching
0N/A * the specified pattern
0N/A * @throws IllegalStateException if this scanner is closed
869N/A */
0N/A public boolean hasNext(Pattern pattern) {
0N/A ensureOpen();
0N/A if (pattern == null)
0N/A throw new NullPointerException();
0N/A hasNextPattern = null;
0N/A saveState();
869N/A
0N/A while (true) {
0N/A if (getCompleteTokenInBuffer(pattern) != null) {
0N/A matchValid = true;
0N/A cacheResult();
0N/A return revertState(true);
0N/A }
869N/A if (needInput)
0N/A readInput();
0N/A else
0N/A return revertState(false);
0N/A }
0N/A }
0N/A
869N/A /**
0N/A * Returns the next token if it matches the specified pattern. This
0N/A * method may block while waiting for input to scan, even if a previous
0N/A * invocation of {@link #hasNext(Pattern)} returned <code>true</code>.
0N/A * If the match is successful, the scanner advances past the input that
0N/A * matched the pattern.
0N/A *
869N/A * @param pattern the pattern to scan for
0N/A * @return the next token
0N/A * @throws NoSuchElementException if no more tokens are available
0N/A * @throws IllegalStateException if this scanner is closed
0N/A */
0N/A public String next(Pattern pattern) {
0N/A ensureOpen();
869N/A if (pattern == null)
0N/A throw new NullPointerException();
0N/A
0N/A // Did we already find this pattern?
0N/A if (hasNextPattern == pattern)
0N/A return getCachedResult();
0N/A clearCaches();
869N/A
0N/A // Search for the pattern
0N/A while (true) {
0N/A String token = getCompleteTokenInBuffer(pattern);
0N/A if (token != null) {
0N/A matchValid = true;
0N/A skipped = false;
869N/A return token;
0N/A }
0N/A if (needInput)
0N/A readInput();
0N/A else
0N/A throwFor();
0N/A }
869N/A }
0N/A
0N/A /**
0N/A * Returns true if there is another line in the input of this scanner.
0N/A * This method may block while waiting for input. The scanner does not
0N/A * advance past any input.
0N/A *
869N/A * @return true if and only if this scanner has another line of input
0N/A * @throws IllegalStateException if this scanner is closed
0N/A */
0N/A public boolean hasNextLine() {
0N/A saveState();
0N/A
0N/A String result = findWithinHorizon(linePattern(), 0);
869N/A if (result != null) {
0N/A MatchResult mr = this.match();
0N/A String lineSep = mr.group(1);
0N/A if (lineSep != null) {
0N/A result = result.substring(0, result.length() -
0N/A lineSep.length());
0N/A cacheResult(result);
869N/A
0N/A } else {
0N/A cacheResult();
0N/A }
0N/A }
0N/A revertState();
0N/A return (result != null);
869N/A }
0N/A
0N/A /**
0N/A * Advances this scanner past the current line and returns the input
0N/A * that was skipped.
0N/A *
0N/A * This method returns the rest of the current line, excluding any line
869N/A * separator at the end. The position is set to the beginning of the next
0N/A * line.
0N/A *
0N/A * <p>Since this method continues to search through the input looking
0N/A * for a line separator, it may buffer all of the input searching for
0N/A * the line to skip if no line separators are present.
0N/A *
869N/A * @return the line that was skipped
0N/A * @throws NoSuchElementException if no line was found
0N/A * @throws IllegalStateException if this scanner is closed
0N/A */
0N/A public String nextLine() {
0N/A if (hasNextPattern == linePattern())
0N/A return getCachedResult();
869N/A clearCaches();
0N/A
0N/A String result = findWithinHorizon(linePattern, 0);
0N/A if (result == null)
0N/A throw new NoSuchElementException("No line found");
0N/A MatchResult mr = this.match();
0N/A String lineSep = mr.group(1);
869N/A if (lineSep != null)
0N/A result = result.substring(0, result.length() - lineSep.length());
0N/A if (result == null)
0N/A throw new NoSuchElementException();
0N/A else
0N/A return result;
0N/A }
869N/A
0N/A // Public methods that ignore delimiters
0N/A
0N/A /**
0N/A * Attempts to find the next occurrence of a pattern constructed from the
0N/A * specified string, ignoring delimiters.
0N/A *
869N/A * <p>An invocation of this method of the form <tt>findInLine(pattern)</tt>
869N/A * behaves in exactly the same way as the invocation
0N/A * <tt>findInLine(Pattern.compile(pattern))</tt>.
0N/A *
0N/A * @param pattern a string specifying the pattern to search for
0N/A * @return the text that matched the specified pattern
0N/A * @throws IllegalStateException if this scanner is closed
0N/A */
0N/A public String findInLine(String pattern) {
869N/A return findInLine(patternCache.forName(pattern));
0N/A }
0N/A
0N/A /**
0N/A * Attempts to find the next occurrence of the specified pattern ignoring
0N/A * delimiters. If the pattern is found before the next line separator, the
0N/A * scanner advances past the input that matched and returns the string that
869N/A * matched the pattern.
0N/A * If no such pattern is detected in the input up to the next line
0N/A * separator, then <code>null</code> is returned and the scanner's
869N/A * position is unchanged. This method may block waiting for input that
869N/A * matches the pattern.
869N/A *
869N/A * <p>Since this method continues to search through the input looking
869N/A * for the specified pattern, it may buffer all of the input searching for
869N/A * the desired token if no line separators are present.
869N/A *
868N/A * @param pattern the pattern to scan for
868N/A * @return the text that matched the specified pattern
868N/A * @throws IllegalStateException if this scanner is closed
868N/A */
869N/A public String findInLine(Pattern pattern) {
868N/A ensureOpen();
868N/A if (pattern == null)
0N/A throw new NullPointerException();
0N/A clearCaches();
0N/A // Expand buffer to include the next newline or end of input
0N/A int endPosition = 0;
869N/A saveState();
0N/A while (true) {
0N/A String token = findPatternInBuffer(separatorPattern(), 0);
0N/A if (token != null) {
824N/A endPosition = matcher.start();
869N/A break; // up to next newline
868N/A }
824N/A if (needInput) {
824N/A readInput();
824N/A } else {
869N/A endPosition = buf.limit();
868N/A break; // up to end of input
869N/A }
869N/A }
868N/A revertState();
824N/A int horizonForLine = endPosition - position;
824N/A // If there is nothing between the current pos and the next
869N/A // newline simply return null, invoking findWithinHorizon
868N/A // with "horizon=0" will scan beyond the line bound.
824N/A if (horizonForLine == 0)
869N/A return null;
868N/A // Search for the pattern
869N/A return findWithinHorizon(pattern, horizonForLine);
868N/A }
869N/A
824N/A /**
824N/A * Attempts to find the next occurrence of a pattern constructed from the
869N/A * specified string, ignoring delimiters.
868N/A *
824N/A * <p>An invocation of this method of the form
869N/A * <tt>findWithinHorizon(pattern)</tt> behaves in exactly the same way as
869N/A * the invocation
868N/A * <tt>findWithinHorizon(Pattern.compile(pattern, horizon))</tt>.
868N/A *
849N/A * @param pattern a string specifying the pattern to search for
824N/A * @return the text that matched the specified pattern
0N/A * @throws IllegalStateException if this scanner is closed
869N/A * @throws IllegalArgumentException if horizon is negative
868N/A */
0N/A public String findWithinHorizon(String pattern, int horizon) {
0N/A return findWithinHorizon(patternCache.forName(pattern), horizon);
0N/A }
0N/A
0N/A /**
869N/A * Attempts to find the next occurrence of the specified pattern.
0N/A *
0N/A * <p>This method searches through the input up to the specified
869N/A * search horizon, ignoring delimiters. If the pattern is found the
869N/A * scanner advances past the input that matched and returns the string
0N/A * that matched the pattern. If no such pattern is detected then the
* null is returned and the scanner's position remains unchanged. This
* method may block waiting for input that matches the pattern.
*
* <p>A scanner will never search more than <code>horizon</code> code
* points beyond its current position. Note that a match may be clipped
* by the horizon; that is, an arbitrary match result may have been
* different if the horizon had been larger. The scanner treats the
* horizon as a transparent, non-anchoring bound (see {@link
* Matcher#useTransparentBounds} and {@link Matcher#useAnchoringBounds}).
*
* <p>If horizon is <code>0</code>, then the horizon is ignored and
* this method continues to search through the input looking for the
* specified pattern without bound. In this case it may buffer all of
* the input searching for the pattern.
*
* <p>If horizon is negative, then an IllegalArgumentException is
* thrown.
*
* @param pattern the pattern to scan for
* @return the text that matched the specified pattern
* @throws IllegalStateException if this scanner is closed
* @throws IllegalArgumentException if horizon is negative
*/
public String findWithinHorizon(Pattern pattern, int horizon) {
ensureOpen();
if (pattern == null)
throw new NullPointerException();
if (horizon < 0)
throw new IllegalArgumentException("horizon < 0");
clearCaches();
// Search for the pattern
while (true) {
String token = findPatternInBuffer(pattern, horizon);
if (token != null) {
matchValid = true;
return token;
}
if (needInput)
readInput();
else
break; // up to end of input
}
return null;
}
/**
* Skips input that matches the specified pattern, ignoring delimiters.
* This method will skip input if an anchored match of the specified
* pattern succeeds.
*
* <p>If a match to the specified pattern is not found at the
* current position, then no input is skipped and a
* <tt>NoSuchElementException</tt> is thrown.
*
* <p>Since this method seeks to match the specified pattern starting at
* the scanner's current position, patterns that can match a lot of
* input (".*", for example) may cause the scanner to buffer a large
* amount of input.
*
* <p>Note that it is possible to skip something without risking a
* <code>NoSuchElementException</code> by using a pattern that can
* match nothing, e.g., <code>sc.skip("[ \t]*")</code>.
*
* @param pattern a string specifying the pattern to skip over
* @return this scanner
* @throws NoSuchElementException if the specified pattern is not found
* @throws IllegalStateException if this scanner is closed
*/
public Scanner skip(Pattern pattern) {
ensureOpen();
if (pattern == null)
throw new NullPointerException();
clearCaches();
// Search for the pattern
while (true) {
String token = matchPatternInBuffer(pattern);
if (token != null) {
matchValid = true;
position = matcher.end();
return this;
}
if (needInput)
readInput();
else
throw new NoSuchElementException();
}
}
/**
* Skips input that matches a pattern constructed from the specified
* string.
*
* <p> An invocation of this method of the form <tt>skip(pattern)</tt>
* behaves in exactly the same way as the invocation
* <tt>skip(Pattern.compile(pattern))</tt>.
*
* @param pattern a string specifying the pattern to skip over
* @return this scanner
* @throws IllegalStateException if this scanner is closed
*/
public Scanner skip(String pattern) {
return skip(patternCache.forName(pattern));
}
// Convenience methods for scanning primitives
/**
* Returns true if the next token in this scanner's input can be
* interpreted as a boolean value using a case insensitive pattern
* created from the string "true|false". The scanner does not
* advance past the input that matched.
*
* @return true if and only if this scanner's next token is a valid
* boolean value
* @throws IllegalStateException if this scanner is closed
*/
public boolean hasNextBoolean() {
return hasNext(boolPattern());
}
/**
* Scans the next token of the input into a boolean value and returns
* that value. This method will throw <code>InputMismatchException</code>
* if the next token cannot be translated into a valid boolean value.
* If the match is successful, the scanner advances past the input that
* matched.
*
* @return the boolean scanned from the input
* @throws InputMismatchException if the next token is not a valid boolean
* @throws NoSuchElementException if input is exhausted
* @throws IllegalStateException if this scanner is closed
*/
public boolean nextBoolean() {
clearCaches();
return Boolean.parseBoolean(next(boolPattern()));
}
/**
* Returns true if the next token in this scanner's input can be
* interpreted as a byte value in the default radix using the
* {@link #nextByte} method. The scanner does not advance past any input.
*
* @return true if and only if this scanner's next token is a valid
* byte value
* @throws IllegalStateException if this scanner is closed
*/
public boolean hasNextByte() {
return hasNextByte(defaultRadix);
}
/**
* Returns true if the next token in this scanner's input can be
* interpreted as a byte value in the specified radix using the
* {@link #nextByte} method. The scanner does not advance past any input.
*
* @param radix the radix used to interpret the token as a byte value
* @return true if and only if this scanner's next token is a valid
* byte value
* @throws IllegalStateException if this scanner is closed
*/
public boolean hasNextByte(int radix) {
setRadix(radix);
boolean result = hasNext(integerPattern());
if (result) { // Cache it
try {
String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ?
processIntegerToken(hasNextResult) :
hasNextResult;
typeCache = Byte.parseByte(s, radix);
} catch (NumberFormatException nfe) {
result = false;
}
}
return result;
}
/**
* Scans the next token of the input as a <tt>byte</tt>.
*
* <p> An invocation of this method of the form
* <tt>nextByte()</tt> behaves in exactly the same way as the
* invocation <tt>nextByte(radix)</tt>, where <code>radix</code>
* is the default radix of this scanner.
*
* @return the <tt>byte</tt> scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Integer</i>
* regular expression, or is out of range
* @throws NoSuchElementException if input is exhausted
* @throws IllegalStateException if this scanner is closed
*/
public byte nextByte() {
return nextByte(defaultRadix);
}
/**
* Scans the next token of the input as a <tt>byte</tt>.
* This method will throw <code>InputMismatchException</code>
* if the next token cannot be translated into a valid byte value as
* described below. If the translation is successful, the scanner advances
* past the input that matched.
*
* <p> If the next token matches the <a
* href="#Integer-regex"><i>Integer</i></a> regular expression defined
* above then the token is converted into a <tt>byte</tt> value as if by
* removing all locale specific prefixes, group separators, and locale
* specific suffixes, then mapping non-ASCII digits into ASCII
* digits via {@link Character#digit Character.digit}, prepending a
* negative sign (-) if the locale specific negative prefixes and suffixes
* were present, and passing the resulting string to
* {@link Byte#parseByte(String, int) Byte.parseByte} with the
* specified radix.
*
* @param radix the radix used to interpret the token as a byte value
* @return the <tt>byte</tt> scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Integer</i>
* regular expression, or is out of range
* @throws NoSuchElementException if input is exhausted
* @throws IllegalStateException if this scanner is closed
*/
public byte nextByte(int radix) {
// Check cached result
if ((typeCache != null) && (typeCache instanceof Byte)
&& this.radix == radix) {
byte val = ((Byte)typeCache).byteValue();
useTypeCache();
return val;
}
setRadix(radix);
clearCaches();
// Search for next byte
try {
String s = next(integerPattern());
if (matcher.group(SIMPLE_GROUP_INDEX) == null)
s = processIntegerToken(s);
return Byte.parseByte(s, radix);
} catch (NumberFormatException nfe) {
position = matcher.start(); // don't skip bad token
throw new InputMismatchException(nfe.getMessage());
}
}
/**
* Returns true if the next token in this scanner's input can be
* interpreted as a short value in the default radix using the
* {@link #nextShort} method. The scanner does not advance past any input.
*
* @return true if and only if this scanner's next token is a valid
* short value in the default radix
* @throws IllegalStateException if this scanner is closed
*/
public boolean hasNextShort() {
return hasNextShort(defaultRadix);
}
/**
* Returns true if the next token in this scanner's input can be
* interpreted as a short value in the specified radix using the
* {@link #nextShort} method. The scanner does not advance past any input.
*
* @param radix the radix used to interpret the token as a short value
* @return true if and only if this scanner's next token is a valid
* short value in the specified radix
* @throws IllegalStateException if this scanner is closed
*/
public boolean hasNextShort(int radix) {
setRadix(radix);
boolean result = hasNext(integerPattern());
if (result) { // Cache it
try {
String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ?
processIntegerToken(hasNextResult) :
hasNextResult;
typeCache = Short.parseShort(s, radix);
} catch (NumberFormatException nfe) {
result = false;
}
}
return result;
}
/**
* Scans the next token of the input as a <tt>short</tt>.
*
* <p> An invocation of this method of the form
* <tt>nextShort()</tt> behaves in exactly the same way as the
* invocation <tt>nextShort(radix)</tt>, where <code>radix</code>
* is the default radix of this scanner.
*
* @return the <tt>short</tt> scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Integer</i>
* regular expression, or is out of range
* @throws NoSuchElementException if input is exhausted
* @throws IllegalStateException if this scanner is closed
*/
public short nextShort() {
return nextShort(defaultRadix);
}
/**
* Scans the next token of the input as a <tt>short</tt>.
* This method will throw <code>InputMismatchException</code>
* if the next token cannot be translated into a valid short value as
* described below. If the translation is successful, the scanner advances
* past the input that matched.
*
* <p> If the next token matches the <a
* href="#Integer-regex"><i>Integer</i></a> regular expression defined
* above then the token is converted into a <tt>short</tt> value as if by
* removing all locale specific prefixes, group separators, and locale
* specific suffixes, then mapping non-ASCII digits into ASCII
* digits via {@link Character#digit Character.digit}, prepending a
* negative sign (-) if the locale specific negative prefixes and suffixes
* were present, and passing the resulting string to
* {@link Short#parseShort(String, int) Short.parseShort} with the
* specified radix.
*
* @param radix the radix used to interpret the token as a short value
* @return the <tt>short</tt> scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Integer</i>
* regular expression, or is out of range
* @throws NoSuchElementException if input is exhausted
* @throws IllegalStateException if this scanner is closed
*/
public short nextShort(int radix) {
// Check cached result
if ((typeCache != null) && (typeCache instanceof Short)
&& this.radix == radix) {
short val = ((Short)typeCache).shortValue();
useTypeCache();
return val;
}
setRadix(radix);
clearCaches();
// Search for next short
try {
String s = next(integerPattern());
if (matcher.group(SIMPLE_GROUP_INDEX) == null)
s = processIntegerToken(s);
return Short.parseShort(s, radix);
} catch (NumberFormatException nfe) {
position = matcher.start(); // don't skip bad token
throw new InputMismatchException(nfe.getMessage());
}
}
/**
* Returns true if the next token in this scanner's input can be
* interpreted as an int value in the default radix using the
* {@link #nextInt} method. The scanner does not advance past any input.
*
* @return true if and only if this scanner's next token is a valid
* int value
* @throws IllegalStateException if this scanner is closed
*/
public boolean hasNextInt() {
return hasNextInt(defaultRadix);
}
/**
* Returns true if the next token in this scanner's input can be
* interpreted as an int value in the specified radix using the
* {@link #nextInt} method. The scanner does not advance past any input.
*
* @param radix the radix used to interpret the token as an int value
* @return true if and only if this scanner's next token is a valid
* int value
* @throws IllegalStateException if this scanner is closed
*/
public boolean hasNextInt(int radix) {
setRadix(radix);
boolean result = hasNext(integerPattern());
if (result) { // Cache it
try {
String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ?
processIntegerToken(hasNextResult) :
hasNextResult;
typeCache = Integer.parseInt(s, radix);
} catch (NumberFormatException nfe) {
result = false;
}
}
return result;
}
/**
* The integer token must be stripped of prefixes, group separators,
* and suffixes, non ascii digits must be converted into ascii digits
* before parse will accept it.
*/
private String processIntegerToken(String token) {
String result = token.replaceAll(""+groupSeparator, "");
boolean isNegative = false;
int preLen = negativePrefix.length();
if ((preLen > 0) && result.startsWith(negativePrefix)) {
isNegative = true;
result = result.substring(preLen);
}
int sufLen = negativeSuffix.length();
if ((sufLen > 0) && result.endsWith(negativeSuffix)) {
isNegative = true;
result = result.substring(result.length() - sufLen,
result.length());
}
if (isNegative)
result = "-" + result;
return result;
}
/**
* Scans the next token of the input as an <tt>int</tt>.
*
* <p> An invocation of this method of the form
* <tt>nextInt()</tt> behaves in exactly the same way as the
* invocation <tt>nextInt(radix)</tt>, where <code>radix</code>
* is the default radix of this scanner.
*
* @return the <tt>int</tt> scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Integer</i>
* regular expression, or is out of range
* @throws NoSuchElementException if input is exhausted
* @throws IllegalStateException if this scanner is closed
*/
public int nextInt() {
return nextInt(defaultRadix);
}
/**
* Scans the next token of the input as an <tt>int</tt>.
* This method will throw <code>InputMismatchException</code>
* if the next token cannot be translated into a valid int value as
* described below. If the translation is successful, the scanner advances
* past the input that matched.
*
* <p> If the next token matches the <a
* href="#Integer-regex"><i>Integer</i></a> regular expression defined
* above then the token is converted into an <tt>int</tt> value as if by
* removing all locale specific prefixes, group separators, and locale
* specific suffixes, then mapping non-ASCII digits into ASCII
* digits via {@link Character#digit Character.digit}, prepending a
* negative sign (-) if the locale specific negative prefixes and suffixes
* were present, and passing the resulting string to
* {@link Integer#parseInt(String, int) Integer.parseInt} with the
* specified radix.
*
* @param radix the radix used to interpret the token as an int value
* @return the <tt>int</tt> scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Integer</i>
* regular expression, or is out of range
* @throws NoSuchElementException if input is exhausted
* @throws IllegalStateException if this scanner is closed
*/
public int nextInt(int radix) {
// Check cached result
if ((typeCache != null) && (typeCache instanceof Integer)
&& this.radix == radix) {
int val = ((Integer)typeCache).intValue();
useTypeCache();
return val;
}
setRadix(radix);
clearCaches();
// Search for next int
try {
String s = next(integerPattern());
if (matcher.group(SIMPLE_GROUP_INDEX) == null)
s = processIntegerToken(s);
return Integer.parseInt(s, radix);
} catch (NumberFormatException nfe) {
position = matcher.start(); // don't skip bad token
throw new InputMismatchException(nfe.getMessage());
}
}
/**
* Returns true if the next token in this scanner's input can be
* interpreted as a long value in the default radix using the
* {@link #nextLong} method. The scanner does not advance past any input.
*
* @return true if and only if this scanner's next token is a valid
* long value
* @throws IllegalStateException if this scanner is closed
*/
public boolean hasNextLong() {
return hasNextLong(defaultRadix);
}
/**
* Returns true if the next token in this scanner's input can be
* interpreted as a long value in the specified radix using the
* {@link #nextLong} method. The scanner does not advance past any input.
*
* @param radix the radix used to interpret the token as a long value
* @return true if and only if this scanner's next token is a valid
* long value
* @throws IllegalStateException if this scanner is closed
*/
public boolean hasNextLong(int radix) {
setRadix(radix);
boolean result = hasNext(integerPattern());
if (result) { // Cache it
try {
String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ?
processIntegerToken(hasNextResult) :
hasNextResult;
typeCache = Long.parseLong(s, radix);
} catch (NumberFormatException nfe) {
result = false;
}
}
return result;
}
/**
* Scans the next token of the input as a <tt>long</tt>.
*
* <p> An invocation of this method of the form
* <tt>nextLong()</tt> behaves in exactly the same way as the
* invocation <tt>nextLong(radix)</tt>, where <code>radix</code>
* is the default radix of this scanner.
*
* @return the <tt>long</tt> scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Integer</i>
* regular expression, or is out of range
* @throws NoSuchElementException if input is exhausted
* @throws IllegalStateException if this scanner is closed
*/
public long nextLong() {
return nextLong(defaultRadix);
}
/**
* Scans the next token of the input as a <tt>long</tt>.
* This method will throw <code>InputMismatchException</code>
* if the next token cannot be translated into a valid long value as
* described below. If the translation is successful, the scanner advances
* past the input that matched.
*
* <p> If the next token matches the <a
* href="#Integer-regex"><i>Integer</i></a> regular expression defined
* above then the token is converted into a <tt>long</tt> value as if by
* removing all locale specific prefixes, group separators, and locale
* specific suffixes, then mapping non-ASCII digits into ASCII
* digits via {@link Character#digit Character.digit}, prepending a
* negative sign (-) if the locale specific negative prefixes and suffixes
* were present, and passing the resulting string to
* {@link Long#parseLong(String, int) Long.parseLong} with the
* specified radix.
*
* @param radix the radix used to interpret the token as an int value
* @return the <tt>long</tt> scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Integer</i>
* regular expression, or is out of range
* @throws NoSuchElementException if input is exhausted
* @throws IllegalStateException if this scanner is closed
*/
public long nextLong(int radix) {
// Check cached result
if ((typeCache != null) && (typeCache instanceof Long)
&& this.radix == radix) {
long val = ((Long)typeCache).longValue();
useTypeCache();
return val;
}
setRadix(radix);
clearCaches();
try {
String s = next(integerPattern());
if (matcher.group(SIMPLE_GROUP_INDEX) == null)
s = processIntegerToken(s);
return Long.parseLong(s, radix);
} catch (NumberFormatException nfe) {
position = matcher.start(); // don't skip bad token
throw new InputMismatchException(nfe.getMessage());
}
}
/**
* The float token must be stripped of prefixes, group separators,
* and suffixes, non ascii digits must be converted into ascii digits
* before parseFloat will accept it.
*
* If there are non-ascii digits in the token these digits must
* be processed before the token is passed to parseFloat.
*/
private String processFloatToken(String token) {
String result = token.replaceAll(groupSeparator, "");
if (!decimalSeparator.equals("\\."))
result = result.replaceAll(decimalSeparator, ".");
boolean isNegative = false;
int preLen = negativePrefix.length();
if ((preLen > 0) && result.startsWith(negativePrefix)) {
isNegative = true;
result = result.substring(preLen);
}
int sufLen = negativeSuffix.length();
if ((sufLen > 0) && result.endsWith(negativeSuffix)) {
isNegative = true;
result = result.substring(result.length() - sufLen,
result.length());
}
if (result.equals(nanString))
result = "NaN";
if (result.equals(infinityString))
result = "Infinity";
if (isNegative)
result = "-" + result;
// Translate non-ASCII digits
Matcher m = NON_ASCII_DIGIT.matcher(result);
if (m.find()) {
StringBuilder inASCII = new StringBuilder();
for (int i=0; i<result.length(); i++) {
char nextChar = result.charAt(i);
if (Character.isDigit(nextChar)) {
int d = Character.digit(nextChar, 10);
if (d != -1)
inASCII.append(d);
else
inASCII.append(nextChar);
} else {
inASCII.append(nextChar);
}
}
result = inASCII.toString();
}
return result;
}
/**
* Returns true if the next token in this scanner's input can be
* interpreted as a float value using the {@link #nextFloat}
* method. The scanner does not advance past any input.
*
* @return true if and only if this scanner's next token is a valid
* float value
* @throws IllegalStateException if this scanner is closed
*/
public boolean hasNextFloat() {
setRadix(10);
boolean result = hasNext(floatPattern());
if (result) { // Cache it
try {
String s = processFloatToken(hasNextResult);
typeCache = Float.valueOf(Float.parseFloat(s));
} catch (NumberFormatException nfe) {
result = false;
}
}
return result;
}
/**
* Scans the next token of the input as a <tt>float</tt>.
* This method will throw <code>InputMismatchException</code>
* if the next token cannot be translated into a valid float value as
* described below. If the translation is successful, the scanner advances
* past the input that matched.
*
* <p> If the next token matches the <a
* href="#Float-regex"><i>Float</i></a> regular expression defined above
* then the token is converted into a <tt>float</tt> value as if by
* removing all locale specific prefixes, group separators, and locale
* specific suffixes, then mapping non-ASCII digits into ASCII
* digits via {@link Character#digit Character.digit}, prepending a
* negative sign (-) if the locale specific negative prefixes and suffixes
* were present, and passing the resulting string to
* {@link Float#parseFloat Float.parseFloat}. If the token matches
* the localized NaN or infinity strings, then either "Nan" or "Infinity"
* is passed to {@link Float#parseFloat(String) Float.parseFloat} as
* appropriate.
*
* @return the <tt>float</tt> scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Float</i>
* regular expression, or is out of range
* @throws NoSuchElementException if input is exhausted
* @throws IllegalStateException if this scanner is closed
*/
public float nextFloat() {
// Check cached result
if ((typeCache != null) && (typeCache instanceof Float)) {
float val = ((Float)typeCache).floatValue();
useTypeCache();
return val;
}
setRadix(10);
clearCaches();
try {
return Float.parseFloat(processFloatToken(next(floatPattern())));
} catch (NumberFormatException nfe) {
position = matcher.start(); // don't skip bad token
throw new InputMismatchException(nfe.getMessage());
}
}
/**
* Returns true if the next token in this scanner's input can be
* interpreted as a double value using the {@link #nextDouble}
* method. The scanner does not advance past any input.
*
* @return true if and only if this scanner's next token is a valid
* double value
* @throws IllegalStateException if this scanner is closed
*/
public boolean hasNextDouble() {
setRadix(10);
boolean result = hasNext(floatPattern());
if (result) { // Cache it
try {
String s = processFloatToken(hasNextResult);
typeCache = Double.valueOf(Double.parseDouble(s));
} catch (NumberFormatException nfe) {
result = false;
}
}
return result;
}
/**
* Scans the next token of the input as a <tt>double</tt>.
* This method will throw <code>InputMismatchException</code>
* if the next token cannot be translated into a valid double value.
* If the translation is successful, the scanner advances past the input
* that matched.
*
* <p> If the next token matches the <a
* href="#Float-regex"><i>Float</i></a> regular expression defined above
* then the token is converted into a <tt>double</tt> value as if by
* removing all locale specific prefixes, group separators, and locale
* specific suffixes, then mapping non-ASCII digits into ASCII
* digits via {@link Character#digit Character.digit}, prepending a
* negative sign (-) if the locale specific negative prefixes and suffixes
* were present, and passing the resulting string to
* {@link Double#parseDouble Double.parseDouble}. If the token matches
* the localized NaN or infinity strings, then either "Nan" or "Infinity"
* is passed to {@link Double#parseDouble(String) Double.parseDouble} as
* appropriate.
*
* @return the <tt>double</tt> scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Float</i>
* regular expression, or is out of range
* @throws NoSuchElementException if the input is exhausted
* @throws IllegalStateException if this scanner is closed
*/
public double nextDouble() {
// Check cached result
if ((typeCache != null) && (typeCache instanceof Double)) {
double val = ((Double)typeCache).doubleValue();
useTypeCache();
return val;
}
setRadix(10);
clearCaches();
// Search for next float
try {
return Double.parseDouble(processFloatToken(next(floatPattern())));
} catch (NumberFormatException nfe) {
position = matcher.start(); // don't skip bad token
throw new InputMismatchException(nfe.getMessage());
}
}
// Convenience methods for scanning multi precision numbers
/**
* Returns true if the next token in this scanner's input can be
* interpreted as a <code>BigInteger</code> in the default radix using the
* {@link #nextBigInteger} method. The scanner does not advance past any
* input.
*
* @return true if and only if this scanner's next token is a valid
* <code>BigInteger</code>
* @throws IllegalStateException if this scanner is closed
*/
public boolean hasNextBigInteger() {
return hasNextBigInteger(defaultRadix);
}
/**
* Returns true if the next token in this scanner's input can be
* interpreted as a <code>BigInteger</code> in the specified radix using
* the {@link #nextBigInteger} method. The scanner does not advance past
* any input.
*
* @param radix the radix used to interpret the token as an integer
* @return true if and only if this scanner's next token is a valid
* <code>BigInteger</code>
* @throws IllegalStateException if this scanner is closed
*/
public boolean hasNextBigInteger(int radix) {
setRadix(radix);
boolean result = hasNext(integerPattern());
if (result) { // Cache it
try {
String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ?
processIntegerToken(hasNextResult) :
hasNextResult;
typeCache = new BigInteger(s, radix);
} catch (NumberFormatException nfe) {
result = false;
}
}
return result;
}
/**
* Scans the next token of the input as a {@link java.math.BigInteger
* BigInteger}.
*
* <p> An invocation of this method of the form
* <tt>nextBigInteger()</tt> behaves in exactly the same way as the
* invocation <tt>nextBigInteger(radix)</tt>, where <code>radix</code>
* is the default radix of this scanner.
*
* @return the <tt>BigInteger</tt> scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Integer</i>
* regular expression, or is out of range
* @throws NoSuchElementException if the input is exhausted
* @throws IllegalStateException if this scanner is closed
*/
public BigInteger nextBigInteger() {
return nextBigInteger(defaultRadix);
}
/**
* Scans the next token of the input as a {@link java.math.BigInteger
* BigInteger}.
*
* <p> If the next token matches the <a
* href="#Integer-regex"><i>Integer</i></a> regular expression defined
* above then the token is converted into a <tt>BigInteger</tt> value as if
* by removing all group separators, mapping non-ASCII digits into ASCII
* digits via the {@link Character#digit Character.digit}, and passing the
* resulting string to the {@link
* java.math.BigInteger#BigInteger(java.lang.String)
* BigInteger(String, int)} constructor with the specified radix.
*
* @param radix the radix used to interpret the token
* @return the <tt>BigInteger</tt> scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Integer</i>
* regular expression, or is out of range
* @throws NoSuchElementException if the input is exhausted
* @throws IllegalStateException if this scanner is closed
*/
public BigInteger nextBigInteger(int radix) {
// Check cached result
if ((typeCache != null) && (typeCache instanceof BigInteger)
&& this.radix == radix) {
BigInteger val = (BigInteger)typeCache;
useTypeCache();
return val;
}
setRadix(radix);
clearCaches();
// Search for next int
try {
String s = next(integerPattern());
if (matcher.group(SIMPLE_GROUP_INDEX) == null)
s = processIntegerToken(s);
return new BigInteger(s, radix);
} catch (NumberFormatException nfe) {
position = matcher.start(); // don't skip bad token
throw new InputMismatchException(nfe.getMessage());
}
}
/**
* Returns true if the next token in this scanner's input can be
* interpreted as a <code>BigDecimal</code> using the
* {@link #nextBigDecimal} method. The scanner does not advance past any
* input.
*
* @return true if and only if this scanner's next token is a valid
* <code>BigDecimal</code>
* @throws IllegalStateException if this scanner is closed
*/
public boolean hasNextBigDecimal() {
setRadix(10);
boolean result = hasNext(decimalPattern());
if (result) { // Cache it
try {
String s = processFloatToken(hasNextResult);
typeCache = new BigDecimal(s);
} catch (NumberFormatException nfe) {
result = false;
}
}
return result;
}
/**
* Scans the next token of the input as a {@link java.math.BigDecimal
* BigDecimal}.
*
* <p> If the next token matches the <a
* href="#Decimal-regex"><i>Decimal</i></a> regular expression defined
* above then the token is converted into a <tt>BigDecimal</tt> value as if
* by removing all group separators, mapping non-ASCII digits into ASCII
* digits via the {@link Character#digit Character.digit}, and passing the
* resulting string to the {@link
* java.math.BigDecimal#BigDecimal(java.lang.String) BigDecimal(String)}
* constructor.
*
* @return the <tt>BigDecimal</tt> scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Decimal</i>
* regular expression, or is out of range
* @throws NoSuchElementException if the input is exhausted
* @throws IllegalStateException if this scanner is closed
*/
public BigDecimal nextBigDecimal() {
// Check cached result
if ((typeCache != null) && (typeCache instanceof BigDecimal)) {
BigDecimal val = (BigDecimal)typeCache;
useTypeCache();
return val;
}
setRadix(10);
clearCaches();
// Search for next float
try {
String s = processFloatToken(next(decimalPattern()));
return new BigDecimal(s);
} catch (NumberFormatException nfe) {
position = matcher.start(); // don't skip bad token
throw new InputMismatchException(nfe.getMessage());
}
}
/**
* Resets this scanner.
*
* <p> Resetting a scanner discards all of its explicit state
* information which may have been changed by invocations of {@link
* #useDelimiter}, {@link #useLocale}, or {@link #useRadix}.
*
* <p> An invocation of this method of the form
* <tt>scanner.reset()</tt> behaves in exactly the same way as the
* invocation
*
* <blockquote><pre>
* scanner.useDelimiter("\\p{javaWhitespace}+")
* .useLocale(Locale.getDefault())
* .useRadix(10);
* </pre></blockquote>
*
* @return this scanner
*
* @since 1.6
*/
public Scanner reset() {
delimPattern = WHITESPACE_PATTERN;
useLocale(Locale.getDefault());
useRadix(10);
clearCaches();
return this;
}
}