- java.lang.Object
-
- java.util.Scanner
-
- All implemented interfaces
-
Closeable,AutoCloseable,Iterator<String>
public final class Scanner extends Object implements Iterator<String>, Closeable
A simple text scanner that can parse primitive types and strings using regular expressions.ScannerIts input is broken into tokens using a delimiter pattern, which by default matches whitespace. The obtained token can then be converted into values of various different types.nextmethod.For example, this code allows the user to
System.inReads number:Scanner sc = new Scanner(System.in); int i = sc.nextInt();As another example, this code allows from a file
myNumbersentry allocationlongType:Scanner sc = new Scanner(new File("myNumbers")); while (sc.hasNextLong()) { long aLong = sc.nextLong(); }The scanner can also use delimiters other than whitespace. This example reads several items 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 blueThe same output can be produced using this code, which parses all four tokens at once using a regular expression:
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();4502201395911Identifies what the scanner usesdefault whitespace delimiter 。
reset()The method resets the value of the scanner delimiter to the default whitespace delimiter, regardless of whether it has been previously changed.The scan operation may block while waiting for input.
next()andhasNext()method and its companion methods (e.g.nextInt()andhasNextInt()) It first skips any input matching the delimiter pattern, and then attempts to return the next token.hasNext()andnext()methods may block waiting for further input.hasNext()whether the method block is associated with itsnext()whether the method will blocknext()。tokens()The method may also block waiting for input.of
findInLine(),findWithinHorizon(),skip(), andfindAll()The independent operation of the method's delimiter pattern. These methods will attempt to match the specified pattern regardless of separators in the input, so they can be used in special cases where separators are irrelevant. These methods may block waiting for more input.when the scanner throws
InputMismatchExceptionwhenthe scanner will not pass the token that caused the exception, so it can be retrieved or skipped by other methods.Depending on the type of delimiter pattern, empty tokens can be returned. For example, the pattern
"\\s+"An empty token will not be returned, because it matches multiple instances of the delimiter."\\s"Mode"\\s"An empty token can be returned because it only passes through one space at a time.The scanner can be from any implementation
ReadableThe interface's object reads text. if the underlying readableread()the method call throwsIOException,Then the scanner will assume that it has reached the end of the input. Can be accessed throughioException()The method retrieves the latest exception thrown by the underlying readable.IOException。When
ScannerWhen closed, if the source implementationCloseableinterface, it will close its input source.ScannerIt is unsafe for multi-threaded use without external synchronization.Unless otherwise specified, it will
nullparameter passed tonullany methodScannerwill cause an exception to be thrownNullPointerException。unless using
useRadix(int)the method sets a different radix, otherwise the scanner will interpret numbers as decimal by default. Regardless of whether the scanner was previously changed,reset()methods all reset the scanner's radix value to10。Localized numbers
Instances of this class can scan numbers in the standard format as well as in the format of the scanner's locale. scannerinitial localeYes
Locale.getDefault(Locale.Category.FORMAT)the value returned by the method; It can be changed viauseLocale()method changes.reset()The method resets the value of the scanner's locale to the initial locale, regardless of whether it was previously changed.The localized format is defined according to the following parameters, which for a particular locale are taken from that locale's.
DecimalFormatObjectdfAnd itsDecimalFormatSymbolsObjectdfs。- 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
Can be accessed throughwithBottomRegular expressionSyntaxcomeSpecifiedcanbythatClassExample analysisisNumbersthe string,whereRmaxYesplaceusedradixinHighestbits(For example,radix10inRmaxYes9)。
- NonAsciiDigit :
-
non-ASCII character c,
Character.isDigit(c)returns true - Non0Digit :
-
[1-Rmax] |NonASCIIDigit - Numbers :
-
[0-Rmax] |NonASCIIDigit - GroupedNumeral :
-
(Non0Digit Digit?Digit? -
(LocalGroupSeparator Numbers bits Numbers)+ ) - Numbers :
-
( (Numbers+ ) |GroupedNumeral) - Integer:
-
( [-+]? (Numbers) ) -
|LocalPositivePrefix Numbers LocalPositiveSuffix -
|LocalNegativePrefix Numbers LocalNegativeSuffix - decimal number :
- Numbers
-
|Numbers LocalDecimalSeparator Numbers* -
|LocalDecimalSeparator Numbers+ - Exponent :
-
( [eE] [+-]?Numbers+ ) - 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]+)? - non-digit :
-
NaN |LocalNan| Infinity |LocalInfinity - SignedNonNumber :
-
( [-+]?NonNumber) -
|LocalPositivePrefix NonNumber LocalPositiveSuffix -
|LocalNegativePrefix NonNumber LocalNegativeSuffix - Float :
-
decimal
|HexFloat|SignedNonNumber
In the above regular expression, whitespace is not significant.
- Starting from the following version:
- 1.5
-
-
Constructor Summary
Constructor Constructor Description Scanner(File source)constructs a newScanner, it generates values scanned from the specified file.Scanner(File source, String charsetName)constructs a newScanner, it generates values scanned from the specified file.Scanner(File source, Charset charset)constructs a newScanner, it generates values scanned from the specified file.Scanner(InputStream source)constructs a newScanner, which produces values scanned from the specified input stream.Scanner(InputStream source, String charsetName)constructs a newScanner, which produces values scanned from the specified input stream.Scanner(InputStream source, Charset charset)constructs a newScanner, which produces values scanned from the specified input stream.Scanner(Readable source)constructs a newScanner, it generates values scanned from the specified source.Scanner(String source)constructs a newScanner, which produces values scanned from the specified string.Scanner(ReadableByteChannel source)constructs a newScanner, it can generate values scanned from the specified channel.Scanner(ReadableByteChannel source, String charsetName)constructs a newScanner, it can generate values scanned from the specified channel.Scanner(ReadableByteChannel source, Charset charset)constructs a newScanner, it can generate values scanned from the specified channel.Scanner(Path source)constructs a newScanner, it generates values scanned from the specified file.Scanner(Path source, String charsetName)constructs a newScanner, it generates values scanned from the specified file.Scanner(Path source, Charset charset)constructs a newScanner, it generates values scanned from the specified file.
-
Method Summary
All methods Instance Methods Specific Methods Variables and types Methods Description voidclose()Closes this scanner.Patterndelimiter()returnPattern这Scannercurrently used to match delimiters.Stream<MatchResult>findAll(String patString)Returns a stream of match results that match the provided pattern string.Stream<MatchResult>findAll(Pattern pattern)Returns the stream of match results from this scanner.StringfindInLine(String pattern)Attempts to find the next pattern constructed from the specified string, ignoring delimiters.StringfindInLine(Pattern pattern)Attempts to find the next match of the specified pattern, ignoring delimiters.StringfindWithinHorizon(String pattern, int horizon)Attempts to find the next pattern constructed from the specified string, ignoring delimiters.StringfindWithinHorizon(Pattern pattern, int horizon)Attempts to find the next match of the specified pattern.booleanhasNext()Returns true if there is another token in this scanner's input.booleanhasNext(String pattern)Returns true if the next token matches the pattern constructed from the specified string.booleanhasNext(Pattern pattern)Returns true if the next complete token matches the specified pattern.booleanhasNextBigDecimal()If the next token in this scanner's input can be usednextBigDecimal()method is interpreted asBigDecimalthen returns true.booleanhasNextBigInteger()If the next token in this scanner's input can be usednextBigInteger()The method interprets in the default radix asBigInteger, then returns true.booleanhasNextBigInteger(int radix)If the next token in this scanner's input can be usednextBigInteger()The method interprets as in the specified radix.BigInteger, then returns true.booleanhasNextBoolean()If usingfromString“true | false”CreateofNot distinguishSizewriteofMode,YesPut this扫描deviceInputinnext tokenExplanationisBoolean value, then returns true.booleanhasNextByte()If usingnextByte()The method returns true if it interprets the next token in this scanner's input as a byte value in the default radix.booleanhasNextByte(int radix)If usingnextByte()Returns true if the next token in this scanner's input can be interpreted as a byte value in the specified radix.booleanhasNextDouble()If usingnextDouble()Returns true if the next token in this scanner's input can be interpreted as a double value.booleanhasNextFloat()If usingnextFloat()Returns true if the next token in this scanner's input can be interpreted as a floating-point value.booleanhasNextInt()If usingnextInt()Returns true if the method interprets the next token in this scanner's input as an int value in the default radix.booleanhasNextInt(int radix)If the next token in this scanner's input can be usednextInt()The method returns true if it interprets the token as an int value in the specified radix.booleanhasNextLine()Returns true if there is another line in this scanner's input.booleanhasNextLong()If usingnextLong()The method returns true if the next token in this scanner's input can be interpreted as a long value in the default radix.booleanhasNextLong(int radix)If usingnextLong()Returns true if the method can interpret the next token in this scanner's input as a long value in the specified radix.booleanhasNextShort()If usingnextShort()Returns true if the method can interpret the next token in this scanner's input as a short value in the default radix.booleanhasNextShort(int radix)If the next token in this scanner's input can be usednextShort()If the method is interpreted as a short value in the specified radix, it returns true.IOExceptionioException()returnIOExceptionfinally thrown by thisScannerbasicReadable。Localelocale()Returns the locale of this scanner.MatchResultmatch()Returns the match result of the last scan operation performed by this scanner.Stringnext()Finds and returns the next complete token from this scanner.Stringnext(String pattern)If it matches the pattern constructed from the specified string, then returns the next token.Stringnext(Pattern pattern)If it matches the specified pattern, returns the next token.BigDecimalnextBigDecimal()Scans the next token of the input asBigDecimal。BigIntegernextBigInteger()Scans the next token of the input asBigInteger。BigIntegernextBigInteger(int radix)Scans the next token of the input asBigInteger。booleannextBoolean()Scans the next token of the input as a boolean value and returns that value.bytenextByte()Scans the next token of the input asbyte。bytenextByte(int radix)Scans the next token of the input asbyte。doublenextDouble()Scans the next token of the input asdouble。floatnextFloat()Scans the next token of the input asfloat。intnextInt()Scans the next token of the input asint。intnextInt(int radix)Scans the next token of the input asint。StringnextLine()Advances this scanner past the current line and returns the skipped input.longnextLong()Scans the next token of the input aslong。longnextLong(int radix)Scans the next token of the input aslong。shortnextShort()Scans the next token of the input asshort。shortnextShort(int radix)Scans the next token of the input asshort。intradix()Returns the default radix of this scanner.voidremove()IteratorThis implementation does not support the remove operation.Scannerreset()Resets this scanner.Scannerskip(String pattern)Skips input that matches a pattern constructed with the specified string.Scannerskip(Pattern pattern)Skips input that matches the specified pattern, ignoring delimiters.Stream<String>tokens()Returns a stream of delimiter-separated tokens from this scanner.StringtoString()Return thisScannerthe string representation ofScanner。ScanneruseDelimiter(String pattern)Sets the delimiter pattern of this scanner to the one from the specified.Stringthe constructed pattern.ScanneruseDelimiter(Pattern pattern)Sets this scanner's delimiting pattern to the specified pattern.ScanneruseLocale(Locale locale)Sets the locale of this scanner to the specified locale.ScanneruseRadix(int radix)Sets this scanner's default radix to the specified radix.-
Class declaring methods java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
-
Interface declaring methods java.util.Iterator
forEachRemaining
-
-
-
-
Constructor Detail
-
Scanner
public Scanner(Readable source)
constructs a newScanner, which can produce values scanned from the specified source.- Parameter
-
source- implementationReadablethe character source of the interface
-
Scanner
public Scanner(InputStream source)
constructs a newScanner, which produces values scanned from the specified input stream. uses the underlying platformdefault charsetConverts bytes in the stream to characters.- Parameter
-
source- The input stream to scan
-
Scanner
public Scanner(InputStream source, String charsetName)
constructs a newScanner, which produces values scanned from the specified input stream. Converts bytes from the stream into characters using the specified charset.- Parameter
-
source- The input stream to scan -
charsetNameThe encoding type used to convert bytes from the stream into characters to be scanned. - Exception
-
IllegalArgumentException- If the specified charset does not exist
-
Scanner
public Scanner(InputStream source, Charset charset)
constructs a newScanner, which produces values scanned from the specified input stream. Converts bytes from the stream into characters using the specified charset.- Parameter
-
source- The input stream to scan -
charsetThe character set used to convert bytes from the file into characters to be scanned. - Starting from the following version:
- 10
-
Scanner
public Scanner(File source) throws FileNotFoundException
constructs a newScanner, it generates values scanned from the specified file. uses the underlying platformdefault charsetConverts the bytes in the file to characters.- Parameter
-
source- The file to scan - Exception
-
FileNotFoundException- If the source is not found
-
Scanner
public Scanner(File source, String charsetName) throws FileNotFoundException
constructs a newScanner, it generates values scanned from the specified file. Converts bytes in a file to characters using the specified character set.- Parameter
-
source- The file to scan -
charsetNameThe encoding type used to convert bytes from the file into characters to be scanned. - Exception
-
FileNotFoundException- If the source cannot be found -
IllegalArgumentException- If the specified encoding is not found
-
Scanner
public Scanner(File source, Charset charset) throws IOException
constructs a newScanner, it generates values scanned from the specified file. Converts bytes in a file to characters using the specified character set.- Parameter
-
source- The file to scan -
charsetThe character set used to convert bytes from the file into characters to be scanned. - Exception
-
IOExceptionIf an I/O error occurs while opening the source. - Starting from the following version:
- 10
-
Scanner
public Scanner(Path source) throws IOException
constructs a newScanner, it generates values scanned from the specified file. uses the underlying platformdefault charsetConverts the bytes in the file to characters.- Parameter
-
source- The path of the file to scan - Exception
-
IOExceptionIf an I/O error occurs while opening the source. - Starting from the following version:
- 1.7
-
Scanner
public Scanner(Path source, String charsetName) throws IOException
constructs a newScanner, it generates values scanned from the specified file. Converts bytes in a file to characters using the specified character set.- Parameter
-
source- The path of the file to scan -
charsetNameThe encoding type used to convert bytes from the file into characters to be scanned. - Exception
-
IOExceptionIf an I/O error occurs while opening the source. -
IllegalArgumentException- If the specified encoding is not found - Starting from the following version:
- 1.7
-
Scanner
public Scanner(Path source, Charset charset) throws IOException
constructs a newScanner, it generates values scanned from the specified file. Converts bytes in a file to characters using the specified character set.- Parameter
-
source- The path of the file to scan -
charsetThe character set used to convert bytes from the file into characters to be scanned. - Exception
-
IOExceptionIf an I/O error occurs while opening the source. - Starting from the following version:
- 10
-
Scanner
public Scanner(String source)
constructs a newScanner, which produces values scanned from the specified string.- Parameter
-
source- The string to scan
-
Scanner
public Scanner(ReadableByteChannel source)
constructs a newScanner, it can generate values scanned from the specified channel. uses the underlying platformdefault charsetConverts the bytes from the source to characters.- Parameter
-
source- The channel to scan
-
Scanner
public Scanner(ReadableByteChannel source, String charsetName)
constructs a newScanner, it can generate values scanned from the specified channel. Converts bytes from the source into characters using the specified charset.- Parameter
-
source- The channel to scan -
charsetNameThe encoding type used to convert bytes from the channel into characters to be scanned. - Exception
-
IllegalArgumentException- If the specified charset does not exist
-
Scanner
public Scanner(ReadableByteChannel source, Charset charset)
constructs a newScanner, it can generate values scanned from the specified channel. Converts bytes from the source into characters using the specified charset.- Parameter
-
source- The channel to scan -
charsetThe encoding type used to convert bytes from the channel into characters to be scanned. - Starting from the following version:
- 10
-
-
Method Detail
-
close
public void close()
Closes this scanner.If this scanner has not yet been closed, then if its underlyingreadablealso implements
Closeableinterface, then the readable will be calledclosemethod. If this scanner has been closed, calling this method will have no effect.Attempting to perform a search operation after the scanner is closed will result in
IllegalStateException。- Specified by:
-
closeIn the interfaceAutoCloseable - Specified by:
-
closeIn the interfaceCloseable
-
ioException
public IOException ioException()
returnIOExceptionfinally thrown by thisScannerbasicReadable。 If no such exception exists, this method returnsnull。- Result
- The last exception readable by this scanner
-
delimiter
public Pattern delimiter()
returnPatternthisScannercurrently used to match delimiters.- Result
- The delimiting pattern of this scanner.
-
useDelimiter
public Scanner useDelimiter(Pattern pattern)
Sets this scanner's delimiting pattern to the specified pattern.- Parameter
-
pattern-patternMode - Result
- this scanner
-
useDelimiter
public Scanner useDelimiter(String pattern)
Sets the delimiter pattern of this scanner to the one from the specified.Stringthe constructed pattern.Call
useDelimiter(pattern)The behavior of this method in the form is identical to callinguseDelimiter(Pattern.compile(pattern))。Call
reset()The method sets the scanner's delimiter todefault 。- Parameter
-
pattern- The string specifying the delimiting pattern - Result
- this scanner
-
locale
public Locale locale()
Returns the locale of this scanner.The scanner's locale affects many elements of the default primitive regular expression matching. see abovelocalized numbers 。
- Result
- The locale of this scanner
-
useLocale
public Scanner useLocale(Locale locale)
Sets the locale of this scanner to the specified locale.The scanner's locale affects many elements of the default primitive regular expression matching. see abovelocalized numbers 。
Call
reset()method sets the scanner's locale toinitial locale 。- Parameter
-
localeThe string specifying the locale to use. - Result
- this scanner
-
radix
public int radix()
Returns the default radix of this scanner.The scanner's radix affects the default numeric elements matched by the regular expression; see abovelocalized numbers 。
- Result
- The default radix of this scanner
-
useRadix
public Scanner useRadix(int radix)
Sets this scanner's default radix to the specified radix.The scanner's radix affects the default numeric elements matched by the regular expression; see abovelocalized numbers 。
if the radix is less than
Character.MIN_RADIXor greater thanCharacter.MAX_RADIX, then throwsIllegalArgumentException。Call
reset()The method sets the scanner's radix to10。- Parameter
-
radix- The radix used when scanning numbers - Result
- this scanner
- Exception
-
IllegalArgumentException- If the radix is out of range
-
match
public MatchResult match()
Returns the match result of the last scan operation performed by this scanner. If no match has been performed, or the last matchIllegalStateExceptionthen this method throwsIllegalStateException。Various
nextmethod ofScannerMakes the results of the match available if they complete without throwing an exception. For example, when calling the method that returns an intnextInt()After the method, this method returnsMatchResultto search for the above-definedIntegerregular expression. likewise,findInLine(),findWithinHorizon()andskip()The method returns a match result if it succeeds.- Result
- The match result of the last matching operation
- Exception
-
IllegalStateException- If no match result is available
-
toString
public String toString()
Return this
Scannerthe string representation ofScanner。Scannerthe string representation ofScannerContains information that may be useful for debugging. The specific format is not specified.
-
hasNext
public boolean hasNext()
Returns true if there is another token in this scanner's input. This method may block while waiting for input to scan. The scanner does not advance past any input.- Specified by:
-
hasNext, interfaceIterator<String> - Result
- Returns true if and only if this scanner has another token.
- Exception
-
IllegalStateException- If this scanner is closed - See also:
-
Iterator
-
next
public String next()
Finds and returns the next complete token from this scanner. The input before and after the completed token matches the delimiter pattern. even if a previous callhasNext()returntrue, this method may also, while waiting for input to be scanned,true。- Specified by:
-
nextinterfaceIterator<String> - Result
- next token
- Exception
-
NoSuchElementException- If no more tokens are available -
IllegalStateException- If this scanner is closed - See also:
-
Iterator
-
remove
public void remove()
IteratorThis implementation does not support the remove operation.- Specified by:
-
removeIn the interfaceIterator<String> - Exception
-
UnsupportedOperationException- If this method is called. - See also:
-
Iterator
-
hasNext
public boolean hasNext(String pattern)
Returns true if the next token matches the pattern constructed from the specified string. The scanner does not advance past any input.Call
hasNext(pattern)The behavior of this method in the form is identical to callinghasNext(Pattern.compile(pattern))。- Parameter
-
pattern- The string specifying the pattern to scan - Result
- Returns true if and only if this scanner has another token that matches the specified pattern.
- Exception
-
IllegalStateException- If this scanner is closed
-
next
public String next(String pattern)
If it matches the pattern constructed from the specified string, then returns the next token. If the match succeeds, the scanner will advance past the input that matches the pattern.Call
next(pattern)The behavior of this method in the form is identical to callingnext(Pattern.compile(pattern))Methodnext(Pattern.compile(pattern))。- Parameter
-
pattern- The string specifying the pattern to scan - Result
- next token
- Exception
-
NoSuchElementException- If no such token is available -
IllegalStateException- If this scanner is closed
-
hasNext
public boolean hasNext(Pattern pattern)
Returns true if the next complete token matches the specified pattern. A complete token is a prefix, and the suffix is the input that matches the delimiter pattern. This method may block while waiting for input. The scanner does not advance past any input.- Parameter
-
pattern- The pattern to scan - Result
- Returns true if and only if this scanner has another token that matches the specified pattern.
- Exception
-
IllegalStateException- If this scanner is closed
-
next
public String next(Pattern pattern)
If it matches the specified pattern, returns the next token. even if a previous callhasNext(Pattern)returntrue, this method may also, while waiting for input to be scanned,true。 If the match succeeds, the scanner will advance past the input that matches the pattern.- Parameter
-
pattern- The pattern to scan - Result
- next token
- Exception
-
NoSuchElementException- If no more tokens are available -
IllegalStateException- If this scanner is closed
-
hasNextLine
public boolean hasNextLine()
Returns true if there is another line in this scanner's input. This method may block while waiting for input. The scanner does not advance past any input.- Result
- Returns true if and only if this scanner has another line of input.
- Exception
-
IllegalStateException- If this scanner is closed
-
nextLine
public String nextLine()
Advances this scanner past the current line and returns the skipped input. 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 the input to find line separators, if no line separator exists, it can buffer all input in order to search for the line to skip.
- Result
- skipped rows
- Exception
-
NoSuchElementException- If no line is found -
IllegalStateException- If this scanner is closed
-
findInLine
public String findInLine(String pattern)
Attempts to find the next pattern constructed from the specified string, ignoring delimiters.Call
findInLine(pattern)The behavior of this method in the form is identical to callingfindInLine(Pattern.compile(pattern))。- Parameter
-
pattern- The string specifying the pattern to search for - Result
- The text that matches the specified pattern
- Exception
-
IllegalStateException- If this scanner is closed
-
findInLine
public String findInLine(Pattern pattern)
Attempts to find the next match of the specified pattern, ignoring delimiters. If the pattern is found before the next line separator, the scanner will advance past the matched input and return the string that matches the pattern. If no such pattern is detected in the input up to the next line separator, then returns [null].nullAnd the scanner's position remains unchanged. This method may block waiting for input that matches the pattern.Since this method continues to search the input for the specified pattern, it can buffer all input needed to search for a token if no line separator exists.
- Parameter
-
pattern- The pattern to scan - Result
- The text that matches the specified pattern
- Exception
-
IllegalStateException- If this scanner is closed
-
findWithinHorizon
public String findWithinHorizon(String pattern, int horizon)
Attempts to find the next pattern constructed from the specified string, ignoring delimiters.Call
findWithinHorizon(pattern)The behavior of this method in the form is identical to callingfindWithinHorizon(Pattern.compile(pattern), horizon)。- Parameter
-
pattern- The string specifying the pattern to search for -
horizon- Search range - Result
- The text that matches the specified pattern
- Exception
-
IllegalStateException- If this scanner is closed -
IllegalArgumentException- If the horizon is negative
-
findWithinHorizon
public String findWithinHorizon(Pattern pattern, int horizon)
Attempts to find the next match of the specified pattern.This method searches the input up to the specified search range, ignoring delimiters. If a pattern is found, the scanner advances past the matched input and returns the string that matches the pattern. If no such pattern is detected, it returns null and the scanner's position remains unchanged. This method may block waiting for input that matches the pattern.
The scanner will never search beyond its current position
horizoncode point. Note that the match may be limited by the horizon; In other words, if the horizon is large, any matching result may differ. The scanner treats the horizon as a transparent non-anchored boundary (seeMatcher.useTransparentBounds(boolean)andMatcher.useAnchoringBounds(boolean))。If horizon is
0, then the horizon is ignored, and this method continues to search the input for the specified pattern without bound. In this case, it may buffer all input searched for the pattern.If the horizon is negative, throws IllegalArgumentException.
- Parameter
-
pattern- The pattern to scan -
horizon- Search range - Result
- The text that matches the specified pattern
- Exception
-
IllegalStateException- If this scanner is closed -
IllegalArgumentException- If the horizon is negative
-
skip
public Scanner skip(Pattern pattern)
Skips input that matches the specified pattern, ignoring delimiters. If the anchored match of the specified pattern succeeds, this method will skip the input.If no match for the specified pattern is found at the current position, no input is skipped and an exception is thrown.
NoSuchElementException。Since this method attempts to match the specified pattern starting from the scanner's current position, patterns that can match a large amount of input (such as ".*") may cause the scanner to buffer a large amount of input.
Note that by using a pattern that cannot match (for example,
sc.skip("[ \t]*")skip some content without riskingNoSuchElementExceptionthe risk.- Parameter
-
pattern- The string specifying the pattern to skip - Result
- this scanner
- Exception
-
NoSuchElementException- If the specified pattern is not found -
IllegalStateException- If this scanner is closed
-
skip
public Scanner skip(String pattern)
Skips input that matches a pattern constructed with the specified string.Call
skip(pattern)The behavior of this method in the form is identical to callingskip(Pattern.compile(pattern))Methodskip(Pattern.compile(pattern))。- Parameter
-
pattern- The string specifying the pattern to skip - Result
- this scanner
- Exception
-
IllegalStateException- If this scanner is closed
-
hasNextBoolean
public boolean hasNextBoolean()
If usingfromString“true | false”CreateofNot distinguishSizewriteofMode,YesPut this扫描deviceInputinnext tokenExplanationisBoolean value, then returns true. The scanner will not advance past the matched input.- Result
- Returns true if and only if this scanner's next token is a valid boolean value.
- Exception
-
IllegalStateException- If this scanner is closed
-
nextBoolean
public boolean nextBoolean()
Scans the next token of the input as a boolean value and returns that value. If the next token cannot be converted to a valid boolean value, this method will throwInputMismatchException。 If the match succeeds, the scanner will advance past the matched input.- Result
- The boolean value scanned from the input
- Exception
-
InputMismatchExceptionIf the next token is not a valid boolean value. -
NoSuchElementException- If the input is exhausted -
IllegalStateException- If this scanner is closed
-
hasNextByte
public boolean hasNextByte()
If usingnextByte()The method returns true if it interprets the next token in this scanner's input as a byte value in the default radix. The scanner does not advance past any input.- Result
- Returns true if and only if this scanner's next token is a valid byte value.
- Exception
-
IllegalStateException- If this scanner is closed
-
hasNextByte
public boolean hasNextByte(int radix)
If usingnextByte()Returns true if the next token in this scanner's input can be interpreted as a byte value in the specified radix. The scanner does not advance past any input.if the radix is less than
Character.MIN_RADIXor greater thanCharacter.MAX_RADIX, then throwsIllegalArgumentException。- Parameter
-
radixThe radix used to interpret the token as a byte value. - Result
- Returns true if and only if this scanner's next token is a valid byte value.
- Exception
-
IllegalStateException- If this scanner is closed -
IllegalArgumentException- If the radix is out of range
-
nextByte
public byte nextByte()
Scans the next token of the input asbyte。Call
nextByte()The behavior of this method in the form is identical to callingnextByte(radix), whereradixis the default radix of this scanner.- Result
-
bytescan from input. - Exception
-
InputMismatchException- If the next token does not matchIntegerThe regular expression does not match, or is out of range. -
NoSuchElementException- If the input is exhausted -
IllegalStateException- If this scanner is closed
-
nextByte
public byte nextByte(int radix)
Scans the next token of the input asbyte。 This method will throw if the next token cannot be converted to a valid byte value.InputMismatchException, as described below. If the translation succeeds, the scanner will advance past the matched input.If the next token matches the above-definedIntegerIf the regular expression matches, the token is converted to
bytevalue, as if by removing all locale-specific prefixes, group separators, and locale-specific suffixes, and then byCharacter.digitMaps non-ASCII digits to ASCII digits,PreconditionIf a locale-specific negative prefix and suffix exist, then the minus sign (-) is passed to the one with the specified radix.Byte.parseByte。if the radix is less than
Character.MIN_RADIXor greater thanCharacter.MAX_RADIX, then throwsIllegalArgumentException。- Parameter
-
radixThe radix used to interpret the token as a byte value. - Result
- scan from input.
byte - Exception
-
InputMismatchException- If the next token does not matchIntegerThe regular expression does not match, 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
-
hasNextShort
public boolean hasNextShort()
If usingnextShort()Returns true if the next token in this scanner's input can be interpreted as a short value in the default radix. The scanner does not advance past any input.- Result
- Returns true if and only if this scanner's next token is a valid short value in the default radix.
- Exception
-
IllegalStateException- If this scanner is closed
-
hasNextShort
public boolean hasNextShort(int radix)
If usingnextShort()Returns true if the next token in this scanner's input can be interpreted as a short value in the specified radix. The scanner does not advance past any input.if the radix is less than
Character.MIN_RADIXor greater thanCharacter.MAX_RADIX, then throwsIllegalArgumentException。- Parameter
-
radixThe radix used to interpret the token as a short value. - Result
- Returns true if and only if this scanner's next token is a valid short value in the specified radix.
- Exception
-
IllegalStateException- If this scanner is closed -
IllegalArgumentException- If the radix is out of range
-
nextShort
public short nextShort()
Scans the next token of the input asshort。Call
nextShort()The behavior of this method in the form is identical to callingnextShort(radix)exactly the same, whereradixis the default radix of this scanner.- Result
- scan from input.
short - Exception
-
InputMismatchException- If the next token does not matchIntegerThe regular expression does not match, or is out of range. -
NoSuchElementException- If the input is exhausted -
IllegalStateException- If this scanner is closed
-
nextShort
public short nextShort(int radix)
Scans the next token of the input asshort。 This method will throw if the next token cannot be converted to a valid short value.InputMismatchException, as described below. If the translation succeeds, the scanner will advance past the matched input.If the next token matches the above-definedIntegerIf the regular expression matches, the token is converted to
shortvalue, as if by removing all locale-specific prefixes, group separators, and locale-specific suffixes, and then byCharacter.digitMaps non-ASCII digits to ASCII digits,PreconditionIf a locale-specific negative prefix and suffix exist, then the minus sign (-) is passed to the one with the specified radix.Short.parseShort。if the radix is less than
Character.MIN_RADIXor greater thanCharacter.MAX_RADIX, then throwsIllegalArgumentException。- Parameter
-
radixThe radix used to interpret the token as a short value. - Result
-
shortscan from input. - Exception
-
InputMismatchException- If the next token does not matchIntegerThe regular expression does not match, 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
-
hasNextInt
public boolean hasNextInt()
If the next token in this scanner's input can be usednextInt()The method returns true if it interprets the token as an int value in the default radix. The scanner does not advance past any input.- Result
- Returns true if and only if this scanner's next token is a valid int value.
- Exception
-
IllegalStateException- If this scanner is closed
-
hasNextInt
public boolean hasNextInt(int radix)
If the next token in this scanner's input can be usednextInt()The method returns true if it interprets the token as an int value in the specified radix. The scanner does not advance past any input.if the radix is less than
Character.MIN_RADIXor greater thanCharacter.MAX_RADIX, then throwsIllegalArgumentException。- Parameter
-
radixThe radix used to interpret the token as an int value. - Result
- Returns true if and only if this scanner's next token is a valid int value.
- Exception
-
IllegalStateException- If this scanner is closed -
IllegalArgumentException- If the radix is out of range
-
nextInt
public int nextInt()
Scans the next token of the input asint。Call
nextInt()The behavior of this method in the form is identical to callingnextInt(radix), whereradixis the default radix of this scanner.- Result
-
intscan from input. - Exception
-
InputMismatchException- If the next token does not matchIntegerThe regular expression does not match, or is out of range. -
NoSuchElementException- If the input is exhausted -
IllegalStateException- If this scanner is closed
-
nextInt
public int nextInt(int radix)
Scans the next token of the input asint。 If the next token cannot be converted to a valid int value, this method will throwInputMismatchException, as described below. If the translation succeeds, the scanner will advance past the matched input.If the next token matches the above-definedIntegerIf the regular expression matches, the token is converted to
intvalue, as if by removing all locale-specific prefixes, group separators, and locale-specific suffixes, and then byCharacter.digitMaps non-ASCII digits to ASCII digits,PreconditionIf locale-specific negative prefix and suffix exist, use the minus sign (-), and pass the resulting string to the specified radix.Integer.parseInt。if the radix is less than
Character.MIN_RADIXor greater thanCharacter.MAX_RADIX, then throwsIllegalArgumentException。- Parameter
-
radixThe radix used to interpret the token as an int value. - Result
-
intscan from input. - Exception
-
InputMismatchException- If the next token does not matchIntegerThe regular expression does not match, 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
-
hasNextLong
public boolean hasNextLong()
If usingnextLong()Returns true if the next token in this scanner's input can be interpreted as a long value in the default radix. The scanner does not advance past any input.- Result
- Returns true if and only if this scanner's next token is a valid long value.
- Exception
-
IllegalStateException- If this scanner is closed
-
hasNextLong
public boolean hasNextLong(int radix)
If the next token in this scanner's input can be usednextLong()The method returns true if it is interpreted as a long value in the specified radix. The scanner does not advance past any input.if the radix is less than
Character.MIN_RADIXor greater thanCharacter.MAX_RADIX, then throwsIllegalArgumentException。- Parameter
-
radixThe radix used to interpret the token as a long value. - Result
- Returns true if and only if this scanner's next token is a valid long value.
- Exception
-
IllegalStateException- If this scanner is closed -
IllegalArgumentException- If the radix is out of range
-
nextLong
public long nextLong()
Scans the next token of the input aslong。Call
nextLong()The behavior of this method in the form is identical to callingnextLong(radix), whereradixis the default radix of this scanner.- Result
-
longscan from input. - Exception
-
InputMismatchException- If the next token does not matchIntegerThe regular expression does not match, or is out of range. -
NoSuchElementException- If the input is exhausted -
IllegalStateException- If this scanner is closed
-
nextLong
public long nextLong(int radix)
Scans the next token of the input aslong。 This method will throw if the next token cannot be converted to a valid long value.InputMismatchException, as described below. If the translation succeeds, the scanner will advance past the matched input.If the next token matches the above-definedIntegerThe regular expression matches,Then willMark converted to
longvalue, as if by removing all locale-specific prefixes, group separators, and locale-specific suffixes, and then byCharacter.digitMaps non-ASCII digits to ASCII digits,PreconditionIf locale-specific negative prefix and suffix exist, use the minus sign (-), and pass the resulting string to the specified radix.Long.parseLong。if the radix is less than
Character.MIN_RADIXor greater thanCharacter.MAX_RADIX, then throwsIllegalArgumentException。- Parameter
-
radixThe radix used to interpret the token as an int value. - Result
- scan from input.
long - Exception
-
InputMismatchException- If the next token does not matchIntegerThe regular expression does not match, 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
-
hasNextFloat
public boolean hasNextFloat()
If usingnextFloat()Returns true if the method can interpret the next token in this scanner's input as a floating-point value. The scanner does not advance past any input.- Result
- Returns true if and only if this scanner's next token is a valid float value.
- Exception
-
IllegalStateException- If this scanner is closed
-
nextFloat
public float nextFloat()
Scans the next token of the input asfloat。 If the next token cannot be converted to a valid floating-point value, this method will throwInputMismatchException, as described below. If the translation succeeds, the scanner will advance past the matched input.If the next token matches the above-definedFloatThe regular expression matches,Then willMark converted to
floatvalue, as if by removing all locale-specific prefixes, group separators, and locale-specific suffixes, and then byCharacter.digitMaps non-ASCII digits to ASCII digits,PreconditionIf there is a locale-specific negative prefix and suffix, the negative sign (-) is used, and the resulting string is passed toFloat.parseFloat。 If the token matches a localized NaN or infinity string, then "Nan" or "Infinity" will be passed as needed toFloat.parseFloat。- Result
- scan from input.
float - Exception
-
InputMismatchException- If the next token does not matchFloatThe regular expression does not match, or is out of range. -
NoSuchElementException- If the input is exhausted -
IllegalStateException- If this scanner is closed
-
hasNextDouble
public boolean hasNextDouble()
If usingnextDouble()Returns true if the next token in this scanner's input can be interpreted as a double value. The scanner does not advance past any input.- Result
- Returns true if and only if this scanner's next token is a valid double value.
- Exception
-
IllegalStateException- If this scanner is closed
-
nextDouble
public double nextDouble()
Scans the next token of the input asdouble。 If the next token cannot be converted to a valid double value, this method will throw an exception.InputMismatchException。 If the translation succeeds, the scanner will advance past the matched input.If the next token matches the above-definedFloatIf the regular expression matches, the token is converted to
doublevalue, as if by removing all locale-specific prefixes, group separators, and locale-specific suffixes, and then byCharacter.digitMaps non-ASCII digits to ASCII digits,PreconditionIf locale-specific negative prefix and suffix exist, then pass the minus sign (-) toDouble.parseDouble。 If the token matches a localized NaN or infinity string, then "Nan" or "Infinity" will be passed as needed toDouble.parseDouble。- Result
- scan from input.
double - Exception
-
InputMismatchException- If the next token does not matchFloatThe regular expression does not match, or is out of range. -
NoSuchElementException- If the input is exhausted -
IllegalStateException- If this scanner is closed
-
hasNextBigInteger
public boolean hasNextBigInteger()
If usingnextBigInteger()The method interprets the next token in this scanner's input as a value in the default radix.BigInteger, then returns true. The scanner does not advance past any input.- Result
- Returns true if and only if this scanner's next token is valid.
BigInteger - Exception
-
IllegalStateException- If this scanner is closed
-
hasNextBigInteger
public boolean hasNextBigInteger(int radix)
If the next token in this scanner's input can be usednextBigInteger()The method interprets as in the specified radix.BigInteger, then returns true. The scanner does not advance past any input.if the radix is less than
Character.MIN_RADIXor greater thanCharacter.MAX_RADIX, then throwsIllegalArgumentException。- Parameter
-
radixThe radix used to interpret the token as an integer. - Result
- Returns true if and only if this scanner's next token is valid.
BigInteger - Exception
-
IllegalStateException- If this scanner is closed -
IllegalArgumentException- If the radix is out of range
-
nextBigInteger
public BigInteger nextBigInteger()
Scans the next token of the input asBigInteger。Call
nextBigInteger()The behavior of this method in the form is identical to callingnextBigInteger(radix), whereradixis the default radix of this scanner.- Result
-
BigIntegerscan from input. - Exception
-
InputMismatchException- If the next token does not matchIntegerThe regular expression does not match, or is out of range. -
NoSuchElementException- If the input is exhausted -
IllegalStateException- If this scanner is closed
-
nextBigInteger
public BigInteger nextBigInteger(int radix)
Scans the next token of the input asBigInteger。If the next token matches the above-definedIntegerIf the regular expression matches, the token is converted to
BigIntegervalue, as if by removing all group separators, byCharacter.digitMaps non-ASCII digits to ASCII digits and passes the resulting string toBigInteger(String, int)the radix specified by the constructor.if the radix is less than
Character.MIN_RADIXor greater thanCharacter.MAX_RADIX, then throwsIllegalArgumentException。- Parameter
-
radix- The radix used to interpret tokens - Result
- scan from input.
BigInteger - Exception
-
InputMismatchException- If the next token does not matchIntegerThe regular expression does not match, 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
-
hasNextBigDecimal
public boolean hasNextBigDecimal()
If the next token in this scanner's input can be usednextBigDecimal()method is interpreted asBigDecimalthen returns true. The scanner does not advance past any input.- Result
- Returns true if and only if this scanner's next token is valid.
BigDecimal - Exception
-
IllegalStateException- If this scanner is closed
-
nextBigDecimal
public BigDecimal nextBigDecimal()
Scans the next token of the input asBigDecimal。If the next token matches the above-definedDecimalIf the regular expression matches, the token is converted to
BigDecimalvalue, as if by removing all group separators, byCharacter.digitMaps non-ASCII digits to ASCII digits and passes the resulting string toBigDecimal(String)Constructor.- Result
- scan from input.
BigDecimal - Exception
-
InputMismatchException- If the next token does not matchdecimalThe regular expression does not match, or is out of range. -
NoSuchElementException- If the input is exhausted -
IllegalStateException- If this scanner is closed
-
reset
public Scanner reset()
Resets this scanner.Resetting a Scanner discards all of its explicit state information that may have been changed by invoking
useDelimiter(),useLocale(), oruseRadix()。Call
scanner.reset()The behavior of this form of this method is exactly the same as the manner of invocation.scanner.useDelimiter("\\p{javaWhitespace}+") .useLocale(Locale.getDefault(Locale.Category.FORMAT)) .useRadix(10);- Result
- this scanner
- Starting from the following version:
- 1.6
-
tokens
public Stream<String> tokens()
Returns a stream of delimiter-separated tokens from this scanner. This stream contains the same tokens that would be returned starting from the current state of this scanner, by repeatedly callingnext()method, untilhasNext()The method returns false.The resulting stream is sequential and ordered. All stream elements are non-null.
Begins scanning using the current state of this scanner when a terminal stream operation is initiated. Pair
close()andioException()Subsequent calls to any method on this scanner other than this one may return undefined results, or may have an indeterminate effect on the returned stream. Returns the source of the streamSpliteratorYesfail-fast , AlsoIf any such call is detected during execution of the stream pipeline, it will make a best effort to throwConcurrentModificationException。After the stream pipeline execution completes, this scanner will be in an indeterminate state and cannot be reused.
If this scanner contains resources that must be released, it should be released by calling its
close()method or by closing the returned stream to close this scanner. Closing the stream will close the underlying scanner. If this scanner is closed when this method is invoked, or if this scanner is closed during stream pipeline execution, then this method throws.IllegalStateException。This method may block waiting for more input.
- API Note:
-
For example, the following code creates a comma-separated list of tokens from a string:
List<String> result = new Scanner("abc,def,,ghi") .useDelimiter(",") .tokens() .collect(Collectors.toList());the result list will contain
"abc","def", empty string, and"ghi"。 - Result
- The continuous stream of token strings
- Exception
-
IllegalStateException- If this scanner is closed - Starting from the following version:
- 9
-
findAll
public Stream<MatchResult> findAll(Pattern pattern)
Returns the stream of match results from this scanner. As long asfindWithinHorizon()When a match is found, the stream will contain the same results in the same order, by callingfindWithinHorizon(pattern, 0)andmatch()returns.The resulting stream is sequential and ordered. All stream elements are non-null.
Begins scanning using the current state of this scanner when a terminal stream operation is initiated. Pair
close()andioException()Subsequent calls to any method on this scanner other than this one may return undefined results, or may have an undefined effect on the returned stream. the source of the returned streamSpliteratorYesfail-fast, if any such invocation is detected during the execution of the stream pipeline, an exception will be thrown on a best-effort basis.ConcurrentModificationException。After the stream pipeline execution completes, this scanner will be in an indeterminate state and cannot be reused.
If this scanner contains resources that must be released, it should be released by calling its
close()method or by closing the returned stream to close this scanner. Closing the stream will close the underlying scanner. If this scanner is closed when this method is invoked, or if this scanner is closed during stream pipeline execution, then this method throws.IllegalStateException。and
findWithinHorizon()Like the method, this method may block waiting for more input, and may buffer an unbounded amount of input searching for a match.- API Note:
-
For example, the following code reads a file and returns a list of all character sequences consisting of seven or more Latin uppercase 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()); } - Parameter
-
pattern- The pattern to match - Result
- A continuous stream of match results
- Exception
-
NullPointerException- If pattern is null -
IllegalStateException- If this scanner is closed - Starting from the following version:
- 9
-
findAll
public Stream<MatchResult> findAll(String patString)
Returns a stream of match results that match the provided pattern string. The effect is equivalent to the following code:scanner.findAll(Pattern.compile(patString))- Parameter
-
patString- Pattern string - Result
- A continuous stream of match results
- Exception
-
NullPointerException- if patString is null -
IllegalStateException- If this scanner is closed -
PatternSyntaxException- If the syntax of the regular expression is invalid - Starting from the following version:
- 9
- See also:
-
Pattern
-
-