Module  java.base
Software package  java.util

Class 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 toSystem.inReads number:

    
         Scanner sc = new Scanner(System.in);
         int i = sc.nextInt();
     

    As another example, this code allows from a filemyNumbersentry 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
         blue
     

    The 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.

    offindInLine() , 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 throwsInputMismatchExceptionwhenthe 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 implementationReadableThe 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 。

    WhenScannerWhen 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 willnullparameter passed tonullany methodScannerwill cause an exception to be thrownNullPointerException 。

    unless usinguseRadix(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 localeYesLocale.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
      void close()
      Closes this scanner.
      Pattern delimiter()
      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.
      String findInLine​(String pattern)
      Attempts to find the next pattern constructed from the specified string, ignoring delimiters.
      String findInLine​(Pattern pattern)
      Attempts to find the next match of the specified pattern, ignoring delimiters.
      String findWithinHorizon​(String pattern, int horizon)
      Attempts to find the next pattern constructed from the specified string, ignoring delimiters.
      String findWithinHorizon​(Pattern pattern, int horizon)
      Attempts to find the next match of the specified pattern.
      boolean hasNext()
      Returns true if there is another token in this scanner's input.
      boolean hasNext​(String pattern)
      Returns true if the next token matches the pattern constructed from the specified string.
      boolean hasNext​(Pattern pattern)
      Returns true if the next complete token matches the specified pattern.
      boolean hasNextBigDecimal()
      If the next token in this scanner's input can be usednextBigDecimal()method is interpreted asBigDecimalthen returns true.
      boolean hasNextBigInteger()
      If the next token in this scanner's input can be usednextBigInteger()The method interprets in the default radix asBigInteger, then returns true.
      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.
      boolean hasNextBoolean()
      If usingfromString“true | false”CreateofNot distinguishSizewriteofMode,YesPut this扫描deviceInputinnext tokenExplanationisBoolean value, then returns true.
      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.
      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.
      boolean hasNextDouble()
      If usingnextDouble()Returns true if the next token in this scanner's input can be interpreted as a double value.
      boolean hasNextFloat()
      If usingnextFloat()Returns true if the next token in this scanner's input can be interpreted as a floating-point value.
      boolean hasNextInt()
      If usingnextInt()Returns true if the method interprets the next token in this scanner's input as an int value in the default radix.
      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.
      boolean hasNextLine()
      Returns true if there is another line in this scanner's input.
      boolean hasNextLong()
      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.
      boolean hasNextLong​(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.
      boolean hasNextShort()
      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.
      boolean hasNextShort​(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.
      IOException ioException()
      returnIOExceptionfinally thrown by thisScannerbasicReadable 。
      Locale locale()
      Returns the locale of this scanner.
      MatchResult match()
      Returns the match result of the last scan operation performed by this scanner.
      String next()
      Finds and returns the next complete token from this scanner.
      String next​(String pattern)
      If it matches the pattern constructed from the specified string, then returns the next token.
      String next​(Pattern pattern)
      If it matches the specified pattern, returns the next token.
      BigDecimal nextBigDecimal()
      Scans the next token of the input asBigDecimal 。
      BigInteger nextBigInteger()
      Scans the next token of the input asBigInteger 。
      BigInteger nextBigInteger​(int radix)
      Scans the next token of the input asBigInteger 。
      boolean nextBoolean()
      Scans the next token of the input as a boolean value and returns that value.
      byte nextByte()
      Scans the next token of the input asbyte 。
      byte nextByte​(int radix)
      Scans the next token of the input asbyte 。
      double nextDouble()
      Scans the next token of the input asdouble 。
      float nextFloat()
      Scans the next token of the input asfloat 。
      int nextInt()
      Scans the next token of the input asint 。
      int nextInt​(int radix)
      Scans the next token of the input asint 。
      String nextLine()
      Advances this scanner past the current line and returns the skipped input.
      long nextLong()
      Scans the next token of the input aslong 。
      long nextLong​(int radix)
      Scans the next token of the input aslong 。
      short nextShort()
      Scans the next token of the input asshort 。
      short nextShort​(int radix)
      Scans the next token of the input asshort 。
      int radix()
      Returns the default radix of this scanner.
      void remove()
      IteratorThis implementation does not support the remove operation.
      Scanner reset()
      Resets this scanner.
      Scanner skip​(String pattern)
      Skips input that matches a pattern constructed with the specified string.
      Scanner skip​(Pattern pattern)
      Skips input that matches the specified pattern, ignoring delimiters.
      Stream<String> tokens()
      Returns a stream of delimiter-separated tokens from this scanner.
      String toString()
      Return thisScannerthe string representation ofScanner 。
      Scanner useDelimiter​(String pattern)
      Sets the delimiter pattern of this scanner to the one from the specified.Stringthe constructed pattern.
      Scanner useDelimiter​(Pattern pattern)
      Sets this scanner's delimiting pattern to the specified pattern.
      Scanner useLocale​(Locale locale)
      Sets the locale of this scanner to the specified locale.
      Scanner useRadix​(int radix)
      Sets this scanner's default radix to the specified radix.
    • 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 implementsCloseableinterface, 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 inIllegalStateException 。

        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.

        CalluseDelimiter(pattern)The behavior of this method in the form is identical to callinguseDelimiter(Pattern.compile(pattern)) 。

        Callreset()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 。

        Callreset()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 thanCharacter.MIN_RADIXor greater thanCharacter.MAX_RADIX, then throwsIllegalArgumentException 。

        Callreset()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 。

        Variousnextmethod 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 thisScannerthe string representation ofScanner 。 Scannerthe string representation ofScannerContains information that may be useful for debugging. The specific format is not specified.

        Override:
        toStringcourse categoryObject
        Result
        The string representation of this scanner
      • 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
      • 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.

        CallhasNext(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.

        Callnext(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.

        CallfindInLine(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.

        CallfindWithinHorizon(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 positionhorizoncode 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 is0, 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.

        Callskip(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 thanCharacter.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 。

        CallnextByte()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 tobytevalue, 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 thanCharacter.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 thanCharacter.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 。

        CallnextShort()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 toshortvalue, 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 thanCharacter.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 thanCharacter.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 。

        CallnextInt()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 tointvalue, 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 thanCharacter.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 thanCharacter.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 。

        CallnextLong()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 tolongvalue, 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 thanCharacter.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 tofloatvalue, 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 todoublevalue, 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 thanCharacter.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 。

        CallnextBigInteger()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
      • 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 toBigDecimalvalue, 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 invokinguseDelimiter() , useLocale(), oruseRadix() 。

        Callscanner.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. Pairclose()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 itsclose()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. Pairclose()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 itsclose()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 。

        andfindWithinHorizon()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