A Scanner breaks its input into tokens using a
delimiter pattern, which by default matches whitespace. The resulting
tokens may then be converted into values of different types using the
various next methods.
For example, this code allows a user to read a number from the console.
var con = System.console(); if (con != null) { Scanner sc = new Scanner(con.reader()); int i = sc.nextInt(); }
This code allows long types to be
assigned from entries in a file myNumbers:
Scanner sc = new Scanner(new File("myNumbers"));
while (sc.hasNextLong()) {
long aLong = sc.nextLong();
}
This code uses a Scanner to read lines from System#in. The
Scanner uses the system property value of
stdin. as the Charset. Specifying
the charset explicitly is important when reading from System.in, as it
may differ from the default charset depending
on the host environment or user configuration:
Scanner sc = new Scanner(System.in, System.getProperty("stdin.encoding"));
while (sc.hasNextLine()) {
String aLine = sc.nextLine();
}
The scanner can also use delimiters other than whitespace. This example reads several items in from a string:
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();
prints the following output:
1 2 red blue
The same output can be generated with this code, which uses a regular expression to parse all four tokens at once:
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input);
s.findInLine("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)");
MatchResult result = s.match();
for (int i=1; i<=result.groupCount(); i++)
System.out.println(result.group(i));
s.close();
The default whitespace delimiter used
by a scanner is as recognized by Character.. The reset()
method will reset the value of the scanner's delimiter to the default
whitespace delimiter regardless of whether it was previously changed.
A scanning operation may block waiting for input.
The next and hasNext methods and their
companion methods (such as nextInt and
hasNextInt) first skip any input that matches the delimiter
pattern, and then attempt to return the next token. Both hasNext()
and next() methods may block waiting for further input. Whether a
hasNext() method blocks has no connection to whether or not its
associated next() method will block. The tokens method
may also block waiting for input.
The findInLine(),
findWithinHorizon(),
skip(), and findAll()
methods operate independently of the delimiter pattern. These methods will
attempt to match the specified pattern with no regard to delimiters in the
input and thus can be used in special circumstances where delimiters are
not relevant. These methods may block waiting for more input.
When a scanner throws an InputMismatchException, the scanner
will not pass the token that caused the exception, so that it may be
retrieved or skipped via some other method.
Depending upon the type of delimiting pattern, empty tokens may be
returned. For example, the pattern "\\s+" will return no empty
tokens since it matches multiple instances of the delimiter. The delimiting
pattern "\\s" could return empty tokens since it only passes one
space at a time.
A scanner can read text from any object which implements the java. interface. If an invocation of the underlying
readable's read() method throws an java. then the scanner assumes that the end of the input
has been reached. The most recent IOException thrown by the
underlying readable can be retrieved via the ioException method.
When a Scanner is closed, it will close its input source
if the source implements the java. interface.
A Scanner is not safe for multithreaded use without
external synchronization.
Unless otherwise mentioned, passing a null parameter into
any method of a Scanner will cause a
NullPointerException to be thrown.
A scanner will default to interpreting numbers as decimal unless a
different radix has been set by using the useRadix method. The
reset method will reset the value of the scanner's radix to
10 regardless of whether it was previously changed.
An instance of this class is capable of scanning numbers in the standard
formats as well as in the formats of the scanner's locale. A scanner's
initial locale is the value returned by the Locale. method; it may be changed via the useLocale() method. The reset method will reset the value of the
scanner's locale to the initial locale regardless of whether it was
previously changed.
The localized formats are defined in terms of the following parameters,
which for a particular locale are taken from that locale's DecimalFormat object, df, and its
DecimalFormatSymbols object,
dfs.
- LocalGroupSeparator
- The character used to separate thousands groups, i.e.,
dfs.getGroupingSeparator()- LocalDecimalSeparator
- The character used for the decimal point, i.e.,
dfs.getDecimalSeparator()- LocalPositivePrefix
- The string that appears before a positive number (may be empty), i.e.,
df.getPositivePrefix()- LocalPositiveSuffix
- The string that appears after a positive number (may be empty), i.e.,
df.getPositiveSuffix()- LocalNegativePrefix
- The string that appears before a negative number (may be empty), i.e.,
df.getNegativePrefix()- LocalNegativeSuffix
- The string that appears after a negative number (may be empty), i.e.,
df.getNegativeSuffix()- LocalNaN
- The string that represents not-a-number for floating-point values, i.e.,
dfs.getNaN()- LocalInfinity
- The string that represents infinity for floating-point values, i.e.,
dfs.getInfinity()
The strings that can be parsed as numbers by an instance of this class are specified in terms of the following regular-expression grammar, where Rmax is the highest digit in the radix being used (for example, Rmax is 9 in base 10).
Character.isDigit (c)
returns true
[1-Rmax] | NonASCIIDigit
[0-Rmax] | NonASCIIDigit
( Non0Digit
Digit?
Digit?
( LocalGroupSeparator
Digit
Digit
Digit)+ )
( ( Digit+ )
| GroupedNumeral)
( [-+]? ( Numeral) )
| LocalPositivePrefix Numeral
LocalPositiveSuffix
| LocalNegativePrefix Numeral
LocalNegativeSuffix
| Numeral
LocalDecimalSeparator
Digit*
| LocalDecimalSeparator
Digit+
( [eE] [+-]? Digit+ )
( [-+]? DecimalNumeral
Exponent? )
| LocalPositivePrefix
DecimalNumeral
LocalPositiveSuffix
Exponent?
| LocalNegativePrefix
DecimalNumeral
LocalNegativeSuffix
Exponent?
[-+]? 0[xX][0-9a-fA-F]*\.[0-9a-fA-F]+
([pP][-+]?[0-9]+)?
NaN
| LocalNan| Infinity
| LocalInfinity
( [-+]? NonNumber)
| LocalPositivePrefix
NonNumber
LocalPositiveSuffix
| LocalNegativePrefix
NonNumber
LocalNegativeSuffix
| HexFloat
| SignedNonNumber
Whitespace is not significant in the above regular expressions.
| Modifier and Type | Class and Description |
|---|---|
| pack-priv class | |
| private static class | Scanner.
Small LRU cache of Patterns. |
| pack-priv class |
| Modifier and Type | Field and Description |
|---|---|
| private static final String | |
| private static volatile Pattern | boolPattern
Fields and an accessor method to match booleans |
| private CharBuffer | |
| private static final int | |
| private boolean | |
| private Pattern | |
| private String | |
| private int | |
| private Pattern | |
| private static final String | |
| private static final Pattern | |
| private Pattern | floatPattern
Fields and methods to match floats and doubles |
| private String | groupSeparator
Locale dependent values used to scan numbers |
| private Pattern | |
| private int | |
| private String | |
| private String | |
| private Pattern | integerPattern
Fields and methods to match bytes, shorts, ints, and longs |
| private IOException | |
| private static final String | |
| private static final String | |
| private static volatile Pattern | |
| private Locale | |
| private final Matcher | |
| private boolean | |
| pack-priv int | |
| private String | |
| private boolean | |
| private String | |
| private String | |
| private static final String | |
| private static final Pattern | |
| private final Scanner. | |
| private int | |
| private String | |
| private String | |
| private int | |
| private int | |
| private static volatile Pattern | separatorPattern
Fields and an accessor method to match line separators |
| private static final int | |
| private boolean | |
| private Readable | |
| private boolean | |
| private Object | |
| private static final Pattern |
| Access | Constructor and Description |
|---|---|
| private | |
| public | |
| public | Scanner(InputStream
An input stream to be scanned source)Constructs a new |
| public | Scanner(InputStream
An input stream to be scanned source, String The encoding type used to convert bytes from the
stream into characters to be scanned charsetName)Constructs a new |
| public | Scanner(InputStream
an input stream to be scanned source, Charset the charset used to convert bytes from the file
into characters to be scanned charset)Constructs a new |
| public | |
| public | |
| public | |
| private | |
| public | |
| public | |
| public | |
| public | |
| public | Scanner(ReadableByteChannel
A channel to scan source)Constructs a new |
| public | Scanner(ReadableByteChannel
A channel to scan source, String The encoding type used to convert bytes from the
channel into characters to be scanned charsetName)Constructs a new |
| public | Scanner(ReadableByteChannel
a channel to scan source, Charset the encoding type used to convert bytes from the
channel into characters to be scanned charset)Constructs a new |
| Modifier and Type | Method and Description |
|---|---|
| private static Pattern | |
| private void | |
| private String | |
| private void | |
| private void | |
| private void | |
| public void | |
| private Pattern | |
| public Pattern | Returns: this scanner's delimiting pattern.Returns the |
| private void | |
| public Stream | |
| public Stream | |
| public String | Returns: the text that matched the specified patterna string specifying the pattern to search for pattern)Attempts to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters. |
| public String | Returns: the text that matched the specified patternthe pattern to scan for pattern)Attempts to find the next occurrence of the specified pattern ignoring delimiters. |
| private boolean | |
| public String | Returns: the text that matched the specified patterna string specifying the pattern to search for pattern, int the search horizon horizon)Attempts to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters. |
| public String | Returns: the text that matched the specified patternthe pattern to scan for pattern, int the search horizon horizon)Attempts to find the next occurrence of the specified pattern. |
| private Pattern | |
| private String | |
| private String | |
| public boolean | Returns: true if and only if this scanner has another tokenImplements java. Returns true if this scanner has another token in its input. |
| public boolean | |
| public boolean | |
| public boolean | Returns: true if and only if this scanner's next token is a validBigDecimalReturns true if the next token in this scanner's input can be
interpreted as a |
| public boolean | Returns: true if and only if this scanner's next token is a validBigIntegerReturns true if the next token in this scanner's input can be
interpreted as a |
| public boolean | Returns: true if and only if this scanner's next token is a validBigIntegerthe radix used to interpret the token as an integer radix)Returns true if the next token in this scanner's input can be
interpreted as a |
| public boolean | Returns: true if and only if this scanner's next token is a valid boolean valueReturns 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". |
| public boolean | Returns: true if and only if this scanner's next token is a valid byte valueReturns true if the next token in this scanner's input can be
interpreted as a byte value in the default radix using the
|
| public boolean | Returns: true if and only if this scanner's next token is a valid byte valuethe radix used to interpret the token as a byte value radix)Returns true if the next token in this scanner's input can be
interpreted as a byte value in the specified radix using the
|
| public boolean | Returns: true if and only if this scanner's next token is a valid double valueReturns true if the next token in this scanner's input can be
interpreted as a double value using the |
| public boolean | Returns: true if and only if this scanner's next token is a valid float valueReturns true if the next token in this scanner's input can be
interpreted as a float value using the |
| public boolean | Returns: true if and only if this scanner's next token is a valid int valueReturns true if the next token in this scanner's input can be
interpreted as an int value in the default radix using the
|
| public boolean | Returns: true if and only if this scanner's next token is a valid int valuethe radix used to interpret the token as an int value radix)Returns true if the next token in this scanner's input can be
interpreted as an int value in the specified radix using the
|
| public boolean | Returns: true if there is a line separator in the remaining input or if the input has other remaining charactersReturns true if there is another line in the input of this scanner. |
| public boolean | Returns: true if and only if this scanner's next token is a valid long valueReturns true if the next token in this scanner's input can be
interpreted as a long value in the default radix using the
|
| public boolean | Returns: true if and only if this scanner's next token is a valid long valuethe radix used to interpret the token as a long value radix)Returns true if the next token in this scanner's input can be
interpreted as a long value in the specified radix using the
|
| public boolean | Returns: true if and only if this scanner's next token is a valid short value in the default radixReturns true if the next token in this scanner's input can be
interpreted as a short value in the default radix using the
|
| public boolean | Returns: true if and only if this scanner's next token is a valid short value in the specified radixthe radix used to interpret the token as a short value radix)Returns true if the next token in this scanner's input can be
interpreted as a short value in the specified radix using the
|
| private boolean | |
| private Pattern | |
| public IOException | Returns: the last exception thrown by this scanner's readableReturns the |
| private static Pattern | |
| public Locale | |
| private static Readable | |
| private static Readable | |
| private static Readable | |
| private static Readable | |
| private static Readable | |
| private boolean | |
| public MatchResult | Returns: a match result for the last match operationReturns the match result of the last scanning operation performed by this scanner. |
| private boolean | |
| public String | Returns: the next tokenImplements java. Finds and returns the next complete token from this scanner. |
| public String | |
| public String | |
| public BigDecimal | Returns: theBigDecimal scanned from the inputScans the next token of the input as a |
| public BigInteger | Returns: theBigInteger scanned from the inputScans the next token of the input as a |
| public BigInteger | Returns: theBigInteger scanned from the inputthe radix used to interpret the token radix)Scans the next token of the input as a |
| public boolean | Returns: the boolean scanned from the inputScans the next token of the input into a boolean value and returns that value. |
| public byte | |
| public byte | Returns: thebyte scanned from the inputthe radix used to interpret the token as a byte value radix)Scans the next token of the input as a |
| public double | Returns: thedouble scanned from the inputScans the next token of the input as a |
| public float | |
| public int | |
| public int | Returns: theint scanned from the inputthe radix used to interpret the token as an int value radix)Scans the next token of the input as an |
| public String | Returns: the line that was skippedAdvances this scanner past the current line and returns the input that was skipped. |
| public long | |
| public long | Returns: thelong scanned from the inputthe radix used to interpret the token as an int value radix)Scans the next token of the input as a |
| public short | |
| public short | Returns: theshort scanned from the inputthe radix used to interpret the token as a short value radix)Scans the next token of the input as a |
| private String | processFloatToken(String token)
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. |
| private String | processIntegerToken(String token)
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. |
| public int | |
| private void | |
| public void | remove()
Overrides default java. The remove operation is not supported by this implementation of
|
| public Scanner | |
| private void | |
| private boolean | |
| private void | |
| private static Pattern | |
| private void | |
| public Scanner | |
| public Scanner | |
| private void | |
| private static Charset | |
| private static CharsetDecoder | |
| public Stream | Returns: a sequential stream of token stringsReturns a stream of delimiter-separated tokens from this scanner. |
| public String | Returns: The string representation of this scannerOverrides java. Returns the string representation of this |
| private void | |
| public Scanner | Returns: this scannerA delimiting pattern pattern)Sets this scanner's delimiting pattern to the specified pattern. |
| public Scanner | Returns: this scannerA string specifying a delimiting pattern pattern)Sets this scanner's delimiting pattern to a pattern constructed from
the specified |
| public Scanner | |
| public Scanner | Returns: this scannerThe radix to use when scanning numbers radix)Sets this scanner's default radix to the specified radix. |
| private void |