Scanner Class
Definition
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
A simple text scanner which can parse primitive types and strings using regular expressions.
[Android.Runtime.Register("java/util/Scanner", DoNotGenerateAcw=true)]
public sealed class Scanner : Java.Lang.Object, IDisposable, Java.Interop.IJavaPeerable, Java.IO.ICloseable, Java.Util.IIterator
[<Android.Runtime.Register("java/util/Scanner", DoNotGenerateAcw=true)>]
type Scanner = class
inherit Object
interface ICloseable
interface IJavaObject
interface IDisposable
interface IJavaPeerable
interface IIterator
- Inheritance
- Attributes
- Implements
Remarks
A simple text scanner which can parse primitive types and strings using regular expressions.
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 System.in
: <blockquote>
{@code
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
}
</blockquote>
As another example, this code allows long
types to be assigned from entries in a file myNumbers
: <blockquote>
{@code
Scanner sc = new Scanner(new File("myNumbers"));
while (sc.hasNextLong()) {
long aLong = sc.nextLong();
}
}
</blockquote>
The scanner can also use delimiters other than whitespace. This example reads several items in from a string: <blockquote>
{@code
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();
}
</blockquote>
prints the following output: <blockquote>
{@code
1
2
red
blue
}
</blockquote>
The same output can be generated with this code, which uses a regular expression to parse all four tokens at once: <blockquote>
{@code
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();
}
</blockquote>
The "default-delimiter">default whitespace delimiter used by a scanner is as recognized by Character#isWhitespace(char) Character.isWhitespace()
. The #reset 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 findInLine()
, #findWithinHorizon findWithinHorizon()
, #skip skip()
, and #findAll 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.lang.Readable
interface. If an invocation of the underlying readable's java.lang.Readable#read read()
method throws an java.io.IOException
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.io.Closeable
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.
<h2> "localized-numbers">Localized numbers</h2>
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">initial locale is the value returned by the java.util.Locale#getDefault(Locale.Category) Locale.getDefault(Locale.Category.FORMAT)
method; it may be changed via the #useLocale 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 java.text.DecimalFormat DecimalFormat
object, df
, and its and java.text.DecimalFormatSymbols DecimalFormatSymbols
object, dfs
.
<blockquote><dl> <dt>LocalGroupSeparator <dd>The character used to separate thousands groups, i.e., dfs.
java.text.DecimalFormatSymbols#getGroupingSeparator getGroupingSeparator()
<dt>LocalDecimalSeparator <dd>The character used for the decimal point, i.e., dfs.
java.text.DecimalFormatSymbols#getDecimalSeparator getDecimalSeparator()
<dt>LocalPositivePrefix <dd>The string that appears before a positive number (may be empty), i.e., df.
java.text.DecimalFormat#getPositivePrefix getPositivePrefix()
<dt>LocalPositiveSuffix <dd>The string that appears after a positive number (may be empty), i.e., df.
java.text.DecimalFormat#getPositiveSuffix getPositiveSuffix()
<dt>LocalNegativePrefix <dd>The string that appears before a negative number (may be empty), i.e., df.
java.text.DecimalFormat#getNegativePrefix getNegativePrefix()
<dt>LocalNegativeSuffix <dd>The string that appears after a negative number (may be empty), i.e., df.
java.text.DecimalFormat#getNegativeSuffix getNegativeSuffix()
<dt>LocalNaN <dd>The string that represents not-a-number for floating-point values, i.e., dfs.
java.text.DecimalFormatSymbols#getNaN getNaN()
<dt>LocalInfinity <dd>The string that represents infinity for floating-point values, i.e., dfs.
java.text.DecimalFormatSymbols#getInfinity getInfinity()
</dl></blockquote>
<h3> "number-syntax">Number syntax</h3>
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).
<dl> <dt>NonAsciiDigit: <dd>A non-ASCII character c for which java.lang.Character#isDigit Character.isDigit
(c)
returns true
<dt>Non0Digit: <dd>[1-
Rmax] |
NonASCIIDigit<dt>Digit: <dd>[0-
Rmax] |
NonASCIIDigit<dt>GroupedNumeral: <dd>(
Non0DigitDigit?
Digit?
<dd> (
LocalGroupSeparatorDigitDigitDigit)+ )
<dt>Numeral: <dd>( (
Digit+ ) |
GroupedNumeral)
<dt>"Integer-regex"><i>Integer</i>:<dd>( [-+]? (
Numeral) )
<dd>|
LocalPositivePrefixNumeralLocalPositiveSuffix<dd>|
LocalNegativePrefixNumeralLocalNegativeSuffix<dt>DecimalNumeral: <dd>Numeral<dd>|
NumeralLocalDecimalSeparatorDigit*
<dd>|
LocalDecimalSeparatorDigit+
<dt>Exponent: <dd>( [eE] [+-]?
Digit+ )
<dt>"Decimal-regex"><i>Decimal</i>:<dd>( [-+]?
DecimalNumeralExponent? )
<dd>|
LocalPositivePrefixDecimalNumeralLocalPositiveSuffixExponent?
<dd>|
LocalNegativePrefixDecimalNumeralLocalNegativeSuffixExponent?
<dt>HexFloat: <dd>[-+]? 0[xX][0-9a-fA-F]*\.[0-9a-fA-F]+ ([pP][-+]?[0-9]+)?
<dt>NonNumber: <dd>NaN |
LocalNan| Infinity |
LocalInfinity<dt>SignedNonNumber: <dd>( [-+]?
NonNumber)
<dd>|
LocalPositivePrefixNonNumberLocalPositiveSuffix<dd>|
LocalNegativePrefixNonNumberLocalNegativeSuffix<dt>"Float-regex"><i>Float</i>: <dd>Decimal|
HexFloat|
SignedNonNumber</dl>
Whitespace is not significant in the above regular expressions.
Added in 1.5.
Java documentation for java.util.Scanner
.
Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.
Constructors
Scanner(File) |
Constructs a new |
Scanner(File, Charset) | |
Scanner(File, String) |
Constructs a new |
Scanner(IPath) |
Constructs a new |
Scanner(IPath, Charset) | |
Scanner(IPath, String) |
Constructs a new |
Scanner(IReadable) |
Constructs a new |
Scanner(IReadableByteChannel) |
Constructs a new |
Scanner(IReadableByteChannel, Charset) | |
Scanner(IReadableByteChannel, String) |
Constructs a new |
Scanner(Stream) |
Constructs a new |
Scanner(Stream, Charset) | |
Scanner(Stream, String) |
Constructs a new |
Scanner(String) |
Constructs a new |
Properties
Class |
Returns the runtime class of this |
Handle |
The handle to the underlying Android instance. (Inherited from Object) |
HasNext |
Returns true if this scanner has another token in its input. |
HasNextBigDecimal |
Returns true if the next token in this scanner's input can be
interpreted as a |
HasNextBigInteger |
Returns true if the next token in this scanner's input can be
interpreted as a |
HasNextBoolean |
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". |
HasNextByte |
Returns true if the next token in this scanner's input can be
interpreted as a byte value in the default radix using the
|
HasNextDouble |
Returns true if the next token in this scanner's input can be
interpreted as a double value using the |
HasNextFloat |
Returns true if the next token in this scanner's input can be
interpreted as a float value using the |
HasNextInt |
Returns true if the next token in this scanner's input can be
interpreted as an int value in the default radix using the
|
HasNextLine |
Returns true if there is another line in the input of this scanner. |
HasNextLong |
Returns true if the next token in this scanner's input can be
interpreted as a long value in the default radix using the
|
HasNextShort |
Returns true if the next token in this scanner's input can be
interpreted as a short value in the default radix using the
|
JniIdentityHashCode | (Inherited from Object) |
JniPeerMembers | |
PeerReference | (Inherited from Object) |
ThresholdClass |
This API supports the Mono for Android infrastructure and is not intended to be used directly from your code. (Inherited from Object) |
ThresholdType |
This API supports the Mono for Android infrastructure and is not intended to be used directly from your code. (Inherited from Object) |
Methods
Clone() |
Creates and returns a copy of this object. (Inherited from Object) |
Close() |
Closes this scanner. |
Delimiter() |
Returns the |
Dispose() | (Inherited from Object) |
Dispose(Boolean) | (Inherited from Object) |
Equals(Object) |
Indicates whether some other object is "equal to" this one. (Inherited from Object) |
FindInLine(Pattern) |
Attempts to find the next occurrence of the specified pattern ignoring delimiters. |
FindInLine(String) |
Attempts to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters. |
FindWithinHorizon(Pattern, Int32) |
Attempts to find the next occurrence of the specified pattern. |
FindWithinHorizon(String, Int32) |
Attempts to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters. |
GetHashCode() |
Returns a hash code value for the object. (Inherited from Object) |
InvokeHasNext(Pattern) |
Returns true if the next complete token matches the specified pattern. |
InvokeHasNext(String) |
Returns true if the next token matches the pattern constructed from the specified string. |
InvokeHasNextBigInteger(Int32) |
Returns true if the next token in this scanner's input can be
interpreted as a |
InvokeHasNextByte(Int32) |
Returns true if the next token in this scanner's input can be
interpreted as a byte value in the specified radix using the
|
InvokeHasNextInt(Int32) |
Returns true if the next token in this scanner's input can be
interpreted as an int value in the specified radix using the
|
InvokeHasNextLong(Int32) |
Returns true if the next token in this scanner's input can be
interpreted as a long value in the specified radix using the
|
InvokeHasNextShort(Int32) |
Returns true if the next token in this scanner's input can be
interpreted as a short value in the specified radix using the
|
IoException() |
Returns the |
JavaFinalize() |
Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. (Inherited from Object) |
Locale() |
Returns this scanner's locale. |
Match() |
Returns the match result of the last scanning operation performed by this scanner. |
Next() |
Finds and returns the next complete token from this scanner. |
Next(Pattern) |
Returns the next token if it matches the specified pattern. |
Next(String) |
Returns the next token if it matches the pattern constructed from the specified string. |
NextBigDecimal() |
Scans the next token of the input as a |
NextBigInteger() |
Scans the next token of the input as a |
NextBigInteger(Int32) |
Scans the next token of the input as a |
NextBoolean() |
Scans the next token of the input into a boolean value and returns that value. |
NextByte() |
Scans the next token of the input as a |
NextByte(Int32) |
Scans the next token of the input as a |
NextDouble() |
Scans the next token of the input as a |
NextFloat() |
Scans the next token of the input as a |
NextInt() |
Scans the next token of the input as an |
NextInt(Int32) |
Scans the next token of the input as an |
NextLine() |
Advances this scanner past the current line and returns the input that was skipped. |
NextLong() |
Scans the next token of the input as a |
NextLong(Int32) |
Scans the next token of the input as a |
NextShort() |
Scans the next token of the input as a |
NextShort(Int32) |
Scans the next token of the input as a |
Notify() |
Wakes up a single thread that is waiting on this object's monitor. (Inherited from Object) |
NotifyAll() |
Wakes up all threads that are waiting on this object's monitor. (Inherited from Object) |
Radix() |
Returns this scanner's default radix. |
Remove() |
The remove operation is not supported by this implementation of
|
Reset() |
Resets this scanner. |
SetHandle(IntPtr, JniHandleOwnership) |
Sets the Handle property. (Inherited from Object) |
Skip(Pattern) |
Skips input that matches the specified pattern, ignoring delimiters. |
Skip(String) |
Skips input that matches a pattern constructed from the specified string. |
ToArray<T>() | (Inherited from Object) |
ToString() |
Returns a string representation of the object. (Inherited from Object) |
UnregisterFromRuntime() | (Inherited from Object) |
UseDelimiter(Pattern) |
Sets this scanner's delimiting pattern to the specified pattern. |
UseDelimiter(String) |
Sets this scanner's delimiting pattern to a pattern constructed from
the specified |
UseLocale(Locale) |
Sets this scanner's locale to the specified locale. |
UseRadix(Int32) |
Sets this scanner's default radix to the specified radix. |
Wait() |
Causes the current thread to wait until it is awakened, typically by being <em>notified</em> or <em>interrupted</em>. (Inherited from Object) |
Wait(Int64) |
Causes the current thread to wait until it is awakened, typically by being <em>notified</em> or <em>interrupted</em>, or until a certain amount of real time has elapsed. (Inherited from Object) |
Wait(Int64, Int32) |
Causes the current thread to wait until it is awakened, typically by being <em>notified</em> or <em>interrupted</em>, or until a certain amount of real time has elapsed. (Inherited from Object) |
Explicit Interface Implementations
IIterator.Next() | |
IJavaPeerable.Disposed() | (Inherited from Object) |
IJavaPeerable.DisposeUnlessReferenced() | (Inherited from Object) |
IJavaPeerable.Finalized() | (Inherited from Object) |
IJavaPeerable.JniManagedPeerState | (Inherited from Object) |
IJavaPeerable.SetJniIdentityHashCode(Int32) | (Inherited from Object) |
IJavaPeerable.SetJniManagedPeerState(JniManagedPeerStates) | (Inherited from Object) |
IJavaPeerable.SetPeerReference(JniObjectReference) | (Inherited from Object) |
Extension Methods
JavaCast<TResult>(IJavaObject) |
Performs an Android runtime-checked type conversion. |
JavaCast<TResult>(IJavaObject) | |
GetJniTypeName(IJavaPeerable) |