Class Scanner
- All Implemented Interfaces:
- Closeable, AutoCloseable, Iterator<String>
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.encoding 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.isWhitespace(). 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 Readable interface.  If an invocation of the underlying
readable's read() method throws an 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 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(int) method. The
reset() method will reset the value of the scanner's radix to
10 regardless of whether it was previously changed.
Localized numbers
 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.getDefault(Locale.Category.FORMAT) 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()
Number syntax
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).
- NonAsciiDigit:
- A non-ASCII character c for which
           Character.isDigit(c)returns true
- Non0Digit:
- [1-Rmax- ] |NonASCIIDigit
- Digit:
- [0-Rmax- ] |NonASCIIDigit
- GroupedNumeral:
- (Non0Digit Digit- ?Digit- ?- (LocalGroupSeparator Digit Digit Digit- )+ )
- Numeral:
- ( (Digit- + ) |GroupedNumeral- )
- Integer:
- ( [-+]? (Numeral- ) )- |LocalPositivePrefix Numeral LocalPositiveSuffix- |LocalNegativePrefix Numeral LocalNegativeSuffix
- DecimalNumeral:
- Numeral
      |Numeral LocalDecimalSeparator Digit*|LocalDecimalSeparator Digit+
- Exponent:
- ( [eE] [+-]?Digit- + )
- Decimal:
- ( [-+]?DecimalNumeral Exponent- ? )- |LocalPositivePrefix DecimalNumeral LocalPositiveSuffix Exponent- ?- |LocalNegativePrefix DecimalNumeral LocalNegativeSuffix Exponent- ?
- HexFloat:
- [-+]? 0[xX][0-9a-fA-F]*\.[0-9a-fA-F]+ ([pP][-+]?[0-9]+)?
- NonNumber:
- NaN |LocalNan- | Infinity |LocalInfinity
- SignedNonNumber:
- ( [-+]?NonNumber- )- |LocalPositivePrefix NonNumber LocalPositiveSuffix- |LocalNegativePrefix NonNumber LocalNegativeSuffix
- Float:
- Decimal
          |HexFloat|SignedNonNumber
Whitespace is not significant in the above regular expressions.
- Since:
- 1.5
- 
Constructor SummaryConstructorsConstructorDescriptionConstructs a newScannerthat produces values scanned from the specified file.Constructs a newScannerthat produces values scanned from the specified file.Constructs a newScannerthat produces values scanned from the specified file.Scanner(InputStream source) Constructs a newScannerthat produces values scanned from the specified input stream.Scanner(InputStream source, String charsetName) Constructs a newScannerthat produces values scanned from the specified input stream.Scanner(InputStream source, Charset charset) Constructs a newScannerthat produces values scanned from the specified input stream.Constructs a newScannerthat produces values scanned from the specified source.Constructs a newScannerthat produces values scanned from the specified string.Scanner(ReadableByteChannel source) Constructs a newScannerthat produces values scanned from the specified channel.Scanner(ReadableByteChannel source, String charsetName) Constructs a newScannerthat produces values scanned from the specified channel.Scanner(ReadableByteChannel source, Charset charset) Constructs a newScannerthat produces values scanned from the specified channel.Constructs a newScannerthat produces values scanned from the specified file.Constructs a newScannerthat produces values scanned from the specified file.Constructs a newScannerthat produces values scanned from the specified file.
- 
Method SummaryModifier and TypeMethodDescriptionvoidclose()Closes this scanner.Returns thePatternthisScanneris currently using to match delimiters.Returns a stream of match results that match the provided pattern string.Returns a stream of match results from this scanner.findInLine(String pattern) Attempts to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters.findInLine(Pattern pattern) Attempts to find the next occurrence of the specified pattern ignoring delimiters.findWithinHorizon(String pattern, int horizon) Attempts to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters.findWithinHorizon(Pattern pattern, int horizon) Attempts to find the next occurrence of the specified pattern.booleanhasNext()Returns true if this scanner has another token in its input.booleanReturns true if the next token matches the pattern constructed from the specified string.booleanReturns true if the next complete token matches the specified pattern.booleanReturns true if the next token in this scanner's input can be interpreted as aBigDecimalusing thenextBigDecimal()method.booleanReturns true if the next token in this scanner's input can be interpreted as aBigIntegerin the default radix using thenextBigInteger()method.booleanhasNextBigInteger(int radix) Returns true if the next token in this scanner's input can be interpreted as aBigIntegerin the specified radix using thenextBigInteger()method.booleanReturns 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".booleanReturns true if the next token in this scanner's input can be interpreted as a byte value in the default radix using thenextByte()method.booleanhasNextByte(int radix) Returns true if the next token in this scanner's input can be interpreted as a byte value in the specified radix using thenextByte()method.booleanReturns true if the next token in this scanner's input can be interpreted as a double value using thenextDouble()method.booleanReturns true if the next token in this scanner's input can be interpreted as a float value using thenextFloat()method.booleanReturns true if the next token in this scanner's input can be interpreted as an int value in the default radix using thenextInt()method.booleanhasNextInt(int radix) Returns true if the next token in this scanner's input can be interpreted as an int value in the specified radix using thenextInt()method.booleanReturns true if there is another line in the input of this scanner.booleanReturns true if the next token in this scanner's input can be interpreted as a long value in the default radix using thenextLong()method.booleanhasNextLong(int radix) Returns true if the next token in this scanner's input can be interpreted as a long value in the specified radix using thenextLong()method.booleanReturns true if the next token in this scanner's input can be interpreted as a short value in the default radix using thenextShort()method.booleanhasNextShort(int radix) Returns true if the next token in this scanner's input can be interpreted as a short value in the specified radix using thenextShort()method.Returns theIOExceptionlast thrown by thisScanner's underlyingReadable.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.Returns the next token if it matches the pattern constructed from the specified string.Returns the next token if it matches the specified pattern.Scans the next token of the input as aBigDecimal.Scans the next token of the input as aBigInteger.nextBigInteger(int radix) Scans the next token of the input as aBigInteger.booleanScans the next token of the input into a boolean value and returns that value.bytenextByte()Scans the next token of the input as abyte.bytenextByte(int radix) Scans the next token of the input as abyte.doubleScans the next token of the input as adouble.floatScans the next token of the input as afloat.intnextInt()Scans the next token of the input as anint.intnextInt(int radix) Scans the next token of the input as anint.nextLine()Advances this scanner past the current line and returns the input that was skipped.longnextLong()Scans the next token of the input as along.longnextLong(int radix) Scans the next token of the input as along.shortScans the next token of the input as ashort.shortnextShort(int radix) Scans the next token of the input as ashort.intradix()Returns this scanner's default radix.voidremove()The remove operation is not supported by this implementation ofIterator.reset()Resets this scanner.Skips input that matches a pattern constructed from the specified string.Skips input that matches the specified pattern, ignoring delimiters.tokens()Returns a stream of delimiter-separated tokens from this scanner.toString()Returns the string representation of thisScanner.useDelimiter(String pattern) Sets this scanner's delimiting pattern to a pattern constructed from the specifiedString.useDelimiter(Pattern pattern) Sets this scanner's delimiting pattern to the specified pattern.Sets this scanner's locale to the specified locale.useRadix(int radix) Sets this scanner's default radix to the specified radix.Methods declared in class Objectclone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitMethods declared in interface IteratorforEachRemaining
- 
Constructor Details- 
Scanner
- 
ScannerConstructs a newScannerthat produces values scanned from the specified input stream. Bytes from the stream are converted into characters using the default charset.- Parameters:
- source- An input stream to be scanned
- See Also:
 
- 
ScannerConstructs a newScannerthat produces values scanned from the specified input stream. Bytes from the stream are converted into characters using the specified charset.- Parameters:
- source- An input stream to be scanned
- charsetName- The encoding type used to convert bytes from the stream into characters to be scanned
- Throws:
- IllegalArgumentException- if the specified character set does not exist
 
- 
ScannerConstructs a newScannerthat produces values scanned from the specified input stream. Bytes from the stream are converted into characters using the specified charset.- Parameters:
- source- an input stream to be scanned
- charset- the charset used to convert bytes from the file into characters to be scanned
- Since:
- 10
 
- 
ScannerConstructs a newScannerthat produces values scanned from the specified file. Bytes from the file are converted into characters using the default charset.- Parameters:
- source- A file to be scanned
- Throws:
- FileNotFoundException- if source is not found
- See Also:
 
- 
ScannerConstructs a newScannerthat produces values scanned from the specified file. Bytes from the file are converted into characters using the specified charset.- Parameters:
- source- A file to be scanned
- charsetName- The encoding type used to convert bytes from the file into characters to be scanned
- Throws:
- FileNotFoundException- if source is not found
- IllegalArgumentException- if the specified encoding is not found
 
- 
ScannerConstructs a newScannerthat produces values scanned from the specified file. Bytes from the file are converted into characters using the specified charset.- Parameters:
- source- A file to be scanned
- charset- The charset used to convert bytes from the file into characters to be scanned
- Throws:
- IOException- if an I/O error occurs opening the source
- Since:
- 10
 
- 
ScannerConstructs a newScannerthat produces values scanned from the specified file. Bytes from the file are converted into characters using the default charset.- Parameters:
- source- the path to the file to be scanned
- Throws:
- IOException- if an I/O error occurs opening source
- Since:
- 1.7
- See Also:
 
- 
ScannerConstructs a newScannerthat produces values scanned from the specified file. Bytes from the file are converted into characters using the specified charset.- Parameters:
- source- the path to the file to be scanned
- charsetName- The encoding type used to convert bytes from the file into characters to be scanned
- Throws:
- IOException- if an I/O error occurs opening source
- IllegalArgumentException- if the specified encoding is not found
- Since:
- 1.7
 
- 
ScannerConstructs a newScannerthat produces values scanned from the specified file. Bytes from the file are converted into characters using the specified charset.- Parameters:
- source- the path to the file to be scanned
- charset- the charset used to convert bytes from the file into characters to be scanned
- Throws:
- IOException- if an I/O error occurs opening the source
- Since:
- 10
 
- 
ScannerConstructs a newScannerthat produces values scanned from the specified string.- Parameters:
- source- A string to scan
 
- 
ScannerConstructs a newScannerthat produces values scanned from the specified channel. Bytes from the source are converted into characters using the default charset.- Parameters:
- source- A channel to scan
- See Also:
 
- 
ScannerConstructs a newScannerthat produces values scanned from the specified channel. Bytes from the source are converted into characters using the specified charset.- Parameters:
- source- A channel to scan
- charsetName- The encoding type used to convert bytes from the channel into characters to be scanned
- Throws:
- IllegalArgumentException- if the specified character set does not exist
 
- 
ScannerConstructs a newScannerthat produces values scanned from the specified channel. Bytes from the source are converted into characters using the specified charset.- Parameters:
- source- a channel to scan
- charset- the encoding type used to convert bytes from the channel into characters to be scanned
- Since:
- 10
 
 
- 
- 
Method Details- 
closepublic void close()Closes this scanner.If this scanner has not yet been closed then if its underlying readable also implements the Closeableinterface then the readable'sclosemethod will be invoked. If this scanner is already closed then invoking this method will have no effect.Attempting to perform search operations after a scanner has been closed will result in an IllegalStateException.- Specified by:
- closein interface- AutoCloseable
- Specified by:
- closein interface- Closeable
 
- 
ioExceptionReturns theIOExceptionlast thrown by thisScanner's underlyingReadable. This method returnsnullif no such exception exists.- Returns:
- the last exception thrown by this scanner's readable
 
- 
delimiterReturns thePatternthisScanneris currently using to match delimiters.- Returns:
- this scanner's delimiting pattern.
 
- 
useDelimiter
- 
useDelimiterSets this scanner's delimiting pattern to a pattern constructed from the specifiedString.An invocation of this method of the form useDelimiter(pattern)behaves in exactly the same way as the invocationuseDelimiter(Pattern.compile(pattern)).Invoking the reset()method will set the scanner's delimiter to the default.- Parameters:
- pattern- A string specifying a delimiting pattern
- Returns:
- this scanner
 
- 
localeReturns this scanner's locale.A scanner's locale affects many elements of its default primitive matching regular expressions; see localized numbers above. - Returns:
- this scanner's locale
 
- 
useLocaleSets this scanner's locale to the specified locale.A scanner's locale affects many elements of its default primitive matching regular expressions; see localized numbers above. Invoking the reset()method will set the scanner's locale to the initial locale.- Parameters:
- locale- A string specifying the locale to use
- Returns:
- this scanner
 
- 
radixpublic int radix()Returns this scanner's default radix.A scanner's radix affects elements of its default number matching regular expressions; see localized numbers above. - Returns:
- the default radix of this scanner
 
- 
useRadixSets this scanner's default radix to the specified radix.A scanner's radix affects elements of its default number matching regular expressions; see localized numbers above. If the radix is less than Character.MIN_RADIXor greater thanCharacter.MAX_RADIX, then anIllegalArgumentExceptionis thrown.Invoking the reset()method will set the scanner's radix to10.- Parameters:
- radix- The radix to use when scanning numbers
- Returns:
- this scanner
- Throws:
- IllegalArgumentException- if radix is out of range
 
- 
matchReturns the match result of the last scanning operation performed by this scanner. This method throwsIllegalStateExceptionif no match has been performed, or if the last match was not successful.The various nextmethods ofScannermake a match result available if they complete without throwing an exception. For instance, after an invocation of thenextInt()method that returned an int, this method returns aMatchResultfor the search of the Integer regular expression defined above. Similarly thefindInLine(),findWithinHorizon(), andskip()methods will make a match available if they succeed.- Returns:
- a match result for the last match operation
- Throws:
- IllegalStateException- If no match result is available
 
- 
toString
- 
hasNextpublic boolean hasNext()Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input.- Specified by:
- hasNextin interface- Iterator<String>
- Returns:
- true if and only if this scanner has another token
- Throws:
- IllegalStateException- if this scanner is closed
- See Also:
 
- 
nextFinds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation ofhasNext()returnedtrue.- Specified by:
- nextin interface- Iterator<String>
- Returns:
- the next token
- Throws:
- NoSuchElementException- if no more tokens are available
- IllegalStateException- if this scanner is closed
- See Also:
 
- 
removepublic void remove()The remove operation is not supported by this implementation ofIterator.- Specified by:
- removein interface- Iterator<String>
- Throws:
- UnsupportedOperationException- if this method is invoked.
- See Also:
 
- 
hasNextReturns true if the next token matches the pattern constructed from the specified string. The scanner does not advance past any input.An invocation of this method of the form hasNext(pattern)behaves in exactly the same way as the invocationhasNext(Pattern.compile(pattern)).- Parameters:
- pattern- a string specifying the pattern to scan
- Returns:
- true if and only if this scanner has another token matching the specified pattern
- Throws:
- IllegalStateException- if this scanner is closed
 
- 
nextReturns the next token if it matches the pattern constructed from the specified string. If the match is successful, the scanner advances past the input that matched the pattern.An invocation of this method of the form next(pattern)behaves in exactly the same way as the invocationnext(Pattern.compile(pattern)).- Parameters:
- pattern- a string specifying the pattern to scan
- Returns:
- the next token
- Throws:
- NoSuchElementException- if no such tokens are available
- IllegalStateException- if this scanner is closed
 
- 
hasNextReturns true if the next complete token matches the specified pattern. A complete token is prefixed and postfixed by input that matches the delimiter pattern. This method may block while waiting for input. The scanner does not advance past any input.- Parameters:
- pattern- the pattern to scan for
- Returns:
- true if and only if this scanner has another token matching the specified pattern
- Throws:
- IllegalStateException- if this scanner is closed
 
- 
nextReturns the next token if it matches the specified pattern. This method may block while waiting for input to scan, even if a previous invocation ofhasNext(Pattern)returnedtrue. If the match is successful, the scanner advances past the input that matched the pattern.- Parameters:
- pattern- the pattern to scan for
- Returns:
- the next token
- Throws:
- NoSuchElementException- if no more tokens are available
- IllegalStateException- if this scanner is closed
 
- 
hasNextLinepublic boolean hasNextLine()Returns true if there is another line in the input of this scanner. This method may block while waiting for input. The scanner does not advance past any input.- Returns:
- true if there is a line separator in the remaining input or if the input has other remaining characters
- Throws:
- IllegalStateException- if this scanner is closed
 
- 
nextLineAdvances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present. - Returns:
- the line that was skipped
- Throws:
- NoSuchElementException- if no line was found
- IllegalStateException- if this scanner is closed
 
- 
findInLineAttempts to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters.An invocation of this method of the form findInLine(pattern)behaves in exactly the same way as the invocationfindInLine(Pattern.compile(pattern)).- Parameters:
- pattern- a string specifying the pattern to search for
- Returns:
- the text that matched the specified pattern
- Throws:
- IllegalStateException- if this scanner is closed
 
- 
findInLineAttempts to find the next occurrence of the specified pattern ignoring delimiters. If the pattern is found before the next line separator, the scanner advances past the input that matched and returns the string that matched the pattern. If no such pattern is detected in the input up to the next line separator, thennullis returned and the scanner's position is unchanged. This method may block waiting for input that matches the pattern.Since this method continues to search through the input looking for the specified pattern, it may buffer all of the input searching for the desired token if no line separators are present. - Parameters:
- pattern- the pattern to scan for
- Returns:
- the text that matched the specified pattern
- Throws:
- IllegalStateException- if this scanner is closed
 
- 
findWithinHorizonAttempts to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters.An invocation of this method of the form findWithinHorizon(pattern)behaves in exactly the same way as the invocationfindWithinHorizon(Pattern.compile(pattern), horizon).- Parameters:
- pattern- a string specifying the pattern to search for
- horizon- the search horizon
- Returns:
- the text that matched the specified pattern
- Throws:
- IllegalStateException- if this scanner is closed
- IllegalArgumentException- if horizon is negative
 
- 
findWithinHorizonAttempts to find the next occurrence of the specified pattern.This method searches through the input up to the specified search horizon, ignoring delimiters. If the pattern is found the scanner advances past the input that matched and returns the string 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. A scanner will never search more than horizoncode 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 (seeMatcher.useTransparentBounds(boolean)andMatcher.useAnchoringBounds(boolean)).If horizon is 0, 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.If horizon is negative, then an IllegalArgumentException is thrown. - Parameters:
- pattern- the pattern to scan for
- horizon- the search horizon
- Returns:
- the text that matched the specified pattern
- Throws:
- IllegalStateException- if this scanner is closed
- IllegalArgumentException- if horizon is negative
 
- 
skipSkips input that matches the specified pattern, ignoring delimiters. This method will skip input if an anchored match of the specified pattern succeeds.If a match to the specified pattern is not found at the current position, then no input is skipped and a NoSuchElementExceptionis thrown.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. Note that it is possible to skip something without risking a NoSuchElementExceptionby using a pattern that can match nothing, e.g.,sc.skip("[ \t]*").- Parameters:
- pattern- the pattern to skip over
- Returns:
- this scanner
- Throws:
- NoSuchElementException- if the specified pattern is not found
- IllegalStateException- if this scanner is closed
 
- 
skipSkips input that matches a pattern constructed from the specified string.An invocation of this method of the form skip(pattern)behaves in exactly the same way as the invocationskip(Pattern.compile(pattern)).- Parameters:
- pattern- a string specifying the pattern to skip over
- Returns:
- this scanner
- Throws:
- IllegalStateException- if this scanner is closed
 
- 
hasNextBooleanpublic boolean 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". The scanner does not advance past the input that matched.- Returns:
- true if and only if this scanner's next token is a valid boolean value
- Throws:
- IllegalStateException- if this scanner is closed
 
- 
nextBooleanpublic boolean nextBoolean()Scans the next token of the input into a boolean value and returns that value. This method will throwInputMismatchExceptionif the next token cannot be translated into a valid boolean value. If the match is successful, the scanner advances past the input that matched.- Returns:
- the boolean scanned from the input
- Throws:
- InputMismatchException- if the next token is not a valid boolean
- NoSuchElementException- if input is exhausted
- IllegalStateException- if this scanner is closed
 
- 
hasNextBytepublic boolean hasNextByte()Returns true if the next token in this scanner's input can be interpreted as a byte value in the default radix using thenextByte()method. The scanner does not advance past any input.- Returns:
- true if and only if this scanner's next token is a valid byte value
- Throws:
- IllegalStateException- if this scanner is closed
 
- 
hasNextBytepublic boolean hasNextByte(int radix) Returns true if the next token in this scanner's input can be interpreted as a byte value in the specified radix using thenextByte()method. The scanner does not advance past any input.If the radix is less than Character.MIN_RADIXor greater thanCharacter.MAX_RADIX, then anIllegalArgumentExceptionis thrown.- Parameters:
- radix- the radix used to interpret the token as a byte value
- Returns:
- true if and only if this scanner's next token is a valid byte value
- Throws:
- IllegalStateException- if this scanner is closed
- IllegalArgumentException- if the radix is out of range
 
- 
nextBytepublic byte nextByte()Scans the next token of the input as abyte.An invocation of this method of the form nextByte()behaves in exactly the same way as the invocationnextByte(radix), whereradixis the default radix of this scanner.- Returns:
- the bytescanned from the input
- Throws:
- InputMismatchException- if the next token does not match the Integer regular expression, or is out of range
- NoSuchElementException- if input is exhausted
- IllegalStateException- if this scanner is closed
 
- 
nextBytepublic byte nextByte(int radix) Scans the next token of the input as abyte. This method will throwInputMismatchExceptionif 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.If the next token matches the Integer regular expression defined above then the token is converted into a bytevalue as if by removing all locale specific prefixes, group separators, and locale specific suffixes, then mapping non-ASCII digits into ASCII digits viaCharacter.digit, prepending a negative sign (-) if the locale specific negative prefixes and suffixes were present, and passing the resulting string toByte.parseBytewith the specified radix.If the radix is less than Character.MIN_RADIXor greater thanCharacter.MAX_RADIX, then anIllegalArgumentExceptionis thrown.- Parameters:
- radix- the radix used to interpret the token as a byte value
- Returns:
- the bytescanned from the input
- Throws:
- InputMismatchException- if the next token does not match the Integer regular expression, or is out of range
- NoSuchElementException- if input is exhausted
- IllegalStateException- if this scanner is closed
- IllegalArgumentException- if the radix is out of range
 
- 
hasNextShortpublic boolean hasNextShort()Returns true if the next token in this scanner's input can be interpreted as a short value in the default radix using thenextShort()method. The scanner does not advance past any input.- Returns:
- 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
 
- 
hasNextShortpublic boolean hasNextShort(int radix) Returns true if the next token in this scanner's input can be interpreted as a short value in the specified radix using thenextShort()method. The scanner does not advance past any input.If the radix is less than Character.MIN_RADIXor greater thanCharacter.MAX_RADIX, then anIllegalArgumentExceptionis thrown.- Parameters:
- radix- the radix used to interpret the token as a short value
- Returns:
- 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
- IllegalArgumentException- if the radix is out of range
 
- 
nextShortpublic short nextShort()Scans the next token of the input as ashort.An invocation of this method of the form nextShort()behaves in exactly the same way as the invocationnextShort(radix), whereradixis the default radix of this scanner.- Returns:
- the shortscanned from the input
- Throws:
- InputMismatchException- if the next token does not match the Integer regular expression, or is out of range
- NoSuchElementException- if input is exhausted
- IllegalStateException- if this scanner is closed
 
- 
nextShortpublic short nextShort(int radix) Scans the next token of the input as ashort. This method will throwInputMismatchExceptionif 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.If the next token matches the Integer regular expression defined above then the token is converted into a shortvalue as if by removing all locale specific prefixes, group separators, and locale specific suffixes, then mapping non-ASCII digits into ASCII digits viaCharacter.digit, prepending a negative sign (-) if the locale specific negative prefixes and suffixes were present, and passing the resulting string toShort.parseShortwith the specified radix.If the radix is less than Character.MIN_RADIXor greater thanCharacter.MAX_RADIX, then anIllegalArgumentExceptionis thrown.- Parameters:
- radix- the radix used to interpret the token as a short value
- Returns:
- the shortscanned from the input
- Throws:
- InputMismatchException- if the next token does not match the Integer regular expression, or is out of range
- NoSuchElementException- if input is exhausted
- IllegalStateException- if this scanner is closed
- IllegalArgumentException- if the radix is out of range
 
- 
hasNextIntpublic boolean hasNextInt()Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using thenextInt()method. The scanner does not advance past any input.- Returns:
- true if and only if this scanner's next token is a valid int value
- Throws:
- IllegalStateException- if this scanner is closed
 
- 
hasNextIntpublic boolean hasNextInt(int radix) Returns true if the next token in this scanner's input can be interpreted as an int value in the specified radix using thenextInt()method. The scanner does not advance past any input.If the radix is less than Character.MIN_RADIXor greater thanCharacter.MAX_RADIX, then anIllegalArgumentExceptionis thrown.- Parameters:
- radix- the radix used to interpret the token as an int value
- Returns:
- true if and only if this scanner's next token is a valid int value
- Throws:
- IllegalStateException- if this scanner is closed
- IllegalArgumentException- if the radix is out of range
 
- 
nextIntpublic int nextInt()Scans the next token of the input as anint.An invocation of this method of the form nextInt()behaves in exactly the same way as the invocationnextInt(radix), whereradixis the default radix of this scanner.- Returns:
- the intscanned from the input
- Throws:
- InputMismatchException- if the next token does not match the Integer regular expression, or is out of range
- NoSuchElementException- if input is exhausted
- IllegalStateException- if this scanner is closed
 
- 
nextIntpublic int nextInt(int radix) Scans the next token of the input as anint. This method will throwInputMismatchExceptionif 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.If the next token matches the Integer regular expression defined above then the token is converted into an intvalue as if by removing all locale specific prefixes, group separators, and locale specific suffixes, then mapping non-ASCII digits into ASCII digits viaCharacter.digit, prepending a negative sign (-) if the locale specific negative prefixes and suffixes were present, and passing the resulting string toInteger.parseIntwith the specified radix.If the radix is less than Character.MIN_RADIXor greater thanCharacter.MAX_RADIX, then anIllegalArgumentExceptionis thrown.- Parameters:
- radix- the radix used to interpret the token as an int value
- Returns:
- the intscanned from the input
- Throws:
- InputMismatchException- if the next token does not match the Integer regular expression, or is out of range
- NoSuchElementException- if input is exhausted
- IllegalStateException- if this scanner is closed
- IllegalArgumentException- if the radix is out of range
 
- 
hasNextLongpublic boolean hasNextLong()Returns true if the next token in this scanner's input can be interpreted as a long value in the default radix using thenextLong()method. The scanner does not advance past any input.- Returns:
- true if and only if this scanner's next token is a valid long value
- Throws:
- IllegalStateException- if this scanner is closed
 
- 
hasNextLongpublic boolean hasNextLong(int radix) Returns true if the next token in this scanner's input can be interpreted as a long value in the specified radix using thenextLong()method. The scanner does not advance past any input.If the radix is less than Character.MIN_RADIXor greater thanCharacter.MAX_RADIX, then anIllegalArgumentExceptionis thrown.- Parameters:
- radix- the radix used to interpret the token as a long value
- Returns:
- true if and only if this scanner's next token is a valid long value
- Throws:
- IllegalStateException- if this scanner is closed
- IllegalArgumentException- if the radix is out of range
 
- 
nextLongpublic long nextLong()Scans the next token of the input as along.An invocation of this method of the form nextLong()behaves in exactly the same way as the invocationnextLong(radix), whereradixis the default radix of this scanner.- Returns:
- the longscanned from the input
- Throws:
- InputMismatchException- if the next token does not match the Integer regular expression, or is out of range
- NoSuchElementException- if input is exhausted
- IllegalStateException- if this scanner is closed
 
- 
nextLongpublic long nextLong(int radix) Scans the next token of the input as along. This method will throwInputMismatchExceptionif 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.If the next token matches the Integer regular expression defined above then the token is converted into a longvalue as if by removing all locale specific prefixes, group separators, and locale specific suffixes, then mapping non-ASCII digits into ASCII digits viaCharacter.digit, prepending a negative sign (-) if the locale specific negative prefixes and suffixes were present, and passing the resulting string toLong.parseLongwith the specified radix.If the radix is less than Character.MIN_RADIXor greater thanCharacter.MAX_RADIX, then anIllegalArgumentExceptionis thrown.- Parameters:
- radix- the radix used to interpret the token as an int value
- Returns:
- the longscanned from the input
- Throws:
- InputMismatchException- if the next token does not match the Integer regular expression, or is out of range
- NoSuchElementException- if input is exhausted
- IllegalStateException- if this scanner is closed
- IllegalArgumentException- if the radix is out of range
 
- 
hasNextFloatpublic boolean hasNextFloat()Returns true if the next token in this scanner's input can be interpreted as a float value using thenextFloat()method. The scanner does not advance past any input.- Returns:
- true if and only if this scanner's next token is a valid float value
- Throws:
- IllegalStateException- if this scanner is closed
 
- 
nextFloatpublic float nextFloat()Scans the next token of the input as afloat. This method will throwInputMismatchExceptionif 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.If the next token matches the Float regular expression defined above then the token is converted into a floatvalue as if by removing all locale specific prefixes, group separators, and locale specific suffixes, then mapping non-ASCII digits into ASCII digits viaCharacter.digit, prepending a negative sign (-) if the locale specific negative prefixes and suffixes were present, and passing the resulting string toFloat.parseFloat. If the token matches the localized NaN or infinity strings, then either "Nan" or "Infinity" is passed toFloat.parseFloatas appropriate.- Returns:
- the floatscanned from the input
- Throws:
- InputMismatchException- if the next token does not match the Float regular expression, or is out of range
- NoSuchElementException- if input is exhausted
- IllegalStateException- if this scanner is closed
 
- 
hasNextDoublepublic boolean hasNextDouble()Returns true if the next token in this scanner's input can be interpreted as a double value using thenextDouble()method. The scanner does not advance past any input.- Returns:
- true if and only if this scanner's next token is a valid double value
- Throws:
- IllegalStateException- if this scanner is closed
 
- 
nextDoublepublic double nextDouble()Scans the next token of the input as adouble. This method will throwInputMismatchExceptionif the next token cannot be translated into a valid double value. If the translation is successful, the scanner advances past the input that matched.If the next token matches the Float regular expression defined above then the token is converted into a doublevalue as if by removing all locale specific prefixes, group separators, and locale specific suffixes, then mapping non-ASCII digits into ASCII digits viaCharacter.digit, prepending a negative sign (-) if the locale specific negative prefixes and suffixes were present, and passing the resulting string toDouble.parseDouble. If the token matches the localized NaN or infinity strings, then either "Nan" or "Infinity" is passed toDouble.parseDoubleas appropriate.- Returns:
- the doublescanned from the input
- Throws:
- InputMismatchException- if the next token does not match the Float regular expression, or is out of range
- NoSuchElementException- if the input is exhausted
- IllegalStateException- if this scanner is closed
 
- 
hasNextBigIntegerpublic boolean hasNextBigInteger()Returns true if the next token in this scanner's input can be interpreted as aBigIntegerin the default radix using thenextBigInteger()method. The scanner does not advance past any input.- Returns:
- true if and only if this scanner's next token is a valid
        BigInteger
- Throws:
- IllegalStateException- if this scanner is closed
 
- 
hasNextBigIntegerpublic boolean hasNextBigInteger(int radix) Returns true if the next token in this scanner's input can be interpreted as aBigIntegerin the specified radix using thenextBigInteger()method. The scanner does not advance past any input.If the radix is less than Character.MIN_RADIXor greater thanCharacter.MAX_RADIX, then anIllegalArgumentExceptionis thrown.- Parameters:
- radix- the radix used to interpret the token as an integer
- Returns:
- true if and only if this scanner's next token is a valid
        BigInteger
- Throws:
- IllegalStateException- if this scanner is closed
- IllegalArgumentException- if the radix is out of range
 
- 
nextBigIntegerScans the next token of the input as aBigInteger.An invocation of this method of the form nextBigInteger()behaves in exactly the same way as the invocationnextBigInteger(radix), whereradixis the default radix of this scanner.- Returns:
- the BigIntegerscanned from the input
- Throws:
- InputMismatchException- if the next token does not match the Integer regular expression, or is out of range
- NoSuchElementException- if the input is exhausted
- IllegalStateException- if this scanner is closed
 
- 
nextBigIntegerScans the next token of the input as aBigInteger.If the next token matches the Integer regular expression defined above then the token is converted into a BigIntegervalue as if by removing all group separators, mapping non-ASCII digits into ASCII digits via theCharacter.digit, and passing the resulting string to theBigInteger(String, int)constructor with the specified radix.If the radix is less than Character.MIN_RADIXor greater thanCharacter.MAX_RADIX, then anIllegalArgumentExceptionis thrown.- Parameters:
- radix- the radix used to interpret the token
- Returns:
- the BigIntegerscanned from the input
- Throws:
- InputMismatchException- if the next token does not match the Integer regular expression, or is out of range
- NoSuchElementException- if the input is exhausted
- IllegalStateException- if this scanner is closed
- IllegalArgumentException- if the radix is out of range
 
- 
hasNextBigDecimalpublic boolean hasNextBigDecimal()Returns true if the next token in this scanner's input can be interpreted as aBigDecimalusing thenextBigDecimal()method. The scanner does not advance past any input.- Returns:
- true if and only if this scanner's next token is a valid
        BigDecimal
- Throws:
- IllegalStateException- if this scanner is closed
 
- 
nextBigDecimalScans the next token of the input as aBigDecimal.If the next token matches the Decimal regular expression defined above then the token is converted into a BigDecimalvalue as if by removing all group separators, mapping non-ASCII digits into ASCII digits via theCharacter.digit, and passing the resulting string to theBigDecimal(String)constructor.- Returns:
- the BigDecimalscanned from the input
- Throws:
- InputMismatchException- if the next token does not match the Decimal regular expression, or is out of range
- NoSuchElementException- if the input is exhausted
- IllegalStateException- if this scanner is closed
 
- 
resetResets this scanner.Resetting a scanner discards all of its explicit state information which may have been changed by invocations of useDelimiter(),useLocale(), oruseRadix().An invocation of this method of the form scanner.reset()behaves in exactly the same way as the invocationscanner.useDelimiter("\\p{javaWhitespace}+") .useLocale(Locale.getDefault(Locale.Category.FORMAT)) .useRadix(10);- Returns:
- this scanner
- Since:
- 1.6
 
- 
tokensReturns a stream of delimiter-separated tokens from this scanner. The stream contains the same tokens that would be returned, starting from this scanner's current state, by calling thenext()method repeatedly until thehasNext()method returns false.The resulting stream is sequential and ordered. All stream elements are non-null. Scanning starts upon initiation of the terminal stream operation, using the current state of this scanner. Subsequent calls to any methods on this scanner other than close()andioException()may return undefined results or may cause undefined effects on the returned stream. The returned stream's sourceSpliteratoris fail-fast and will, on a best-effort basis, throw aConcurrentModificationExceptionif any such calls are detected during stream pipeline execution.After stream pipeline execution completes, this scanner is left in an indeterminate state and cannot be reused. If this scanner contains a resource that must be released, this scanner should be closed, either by calling its close()method, or by closing the returned stream. Closing the stream will close the underlying scanner.IllegalStateExceptionis thrown if the scanner has been closed when this method is called, or if this scanner is closed during stream pipeline execution.This method might block waiting for more input. - API Note:
- For example, the following code will create a list of
comma-delimited tokens from a string:
List<String> result = new Scanner("abc,def,,ghi") .useDelimiter(",") .tokens() .collect(Collectors.toList());The resulting list would contain "abc","def", the empty string, and"ghi".
- Returns:
- a sequential stream of token strings
- Throws:
- IllegalStateException- if this scanner is closed
- Since:
- 9
 
- 
findAllReturns a stream of match results from this scanner. The stream contains the same results in the same order that would be returned by callingfindWithinHorizon(pattern, 0)and thenmatch()successively as long asfindWithinHorizon()finds matches.The resulting stream is sequential and ordered. All stream elements are non-null. Scanning starts upon initiation of the terminal stream operation, using the current state of this scanner. Subsequent calls to any methods on this scanner other than close()andioException()may return undefined results or may cause undefined effects on the returned stream. The returned stream's sourceSpliteratoris fail-fast and will, on a best-effort basis, throw aConcurrentModificationExceptionif any such calls are detected during stream pipeline execution.After stream pipeline execution completes, this scanner is left in an indeterminate state and cannot be reused. If this scanner contains a resource that must be released, this scanner should be closed, either by calling its close()method, or by closing the returned stream. Closing the stream will close the underlying scanner.IllegalStateExceptionis thrown if the scanner has been closed when this method is called, or if this scanner is closed during stream pipeline execution.As with the findWithinHorizon()methods, this method might block waiting for additional input, and it might buffer an unbounded amount of input searching for a match.- API Note:
- For example, the following code will read a file and return a list
of all sequences of characters consisting of seven or more Latin capital
letters:
try (Scanner sc = new Scanner(Path.of("input.txt"))) { Pattern pat = Pattern.compile("[A-Z]{7,}"); List<String> capWords = sc.findAll(pat) .map(MatchResult::group) .collect(Collectors.toList()); }
- Parameters:
- pattern- the pattern to be matched
- Returns:
- a sequential stream of match results
- Throws:
- NullPointerException- if pattern is null
- IllegalStateException- if this scanner is closed
- Since:
- 9
 
- 
findAllReturns a stream of match results that match the provided pattern string. The effect is equivalent to the following code:scanner.findAll(Pattern.compile(patString))- Parameters:
- patString- the pattern string
- Returns:
- a sequential stream of match results
- Throws:
- NullPointerException- if patString is null
- IllegalStateException- if this scanner is closed
- PatternSyntaxException- if the regular expression's syntax is invalid
- Since:
- 9
- See Also:
 
 
-