APIdia Launch Partner
Top Description Inners Fields Constructors Methods
java.util

public final Class Scanner

extends Object
implements Iterator<String>, Closeable
Class Inheritance
All Implemented Interfaces
java.io.Closeable, java.lang.AutoCloseable, java.util.Iterator
Imports
java.io.Closeable, .File, .FileInputStream, .FileNotFoundException, .IOException, .InputStream, .InputStreamReader, .Reader, java.math.BigDecimal, .BigInteger, java.nio.CharBuffer, java.nio.channels.Channels, .ReadableByteChannel, java.nio.charset.Charset, .CharsetDecoder, .IllegalCharsetNameException, .UnsupportedCharsetException, java.nio.file.Path, .Files, java.text.DecimalFormat, .DecimalFormatSymbols, .NumberFormat, java.text.spi.NumberFormatProvider, java.util.function.Consumer, java.util.regex.MatchResult, .Matcher, .Pattern, .PatternSyntaxException, java.util.stream.Stream, .StreamSupport, sun.util.locale.provider.LocaleProviderAdapter, .ResourceBundleBasedAdapter

A simple text scanner which can parse primitive types and strings using regular expressions.

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

For example, this code allows a user to read a number from the console.

var con = System.console(); if (con != null) { Scanner sc = new Scanner(con.reader()); int i = sc.nextInt(); }
var con = System.console();
if (con != null) {
    Scanner sc = new Scanner(con.reader());
    int i = sc.nextInt();
}

This code allows long types to be assigned from entries in a file myNumbers:

Scanner sc = new Scanner(new File("myNumbers")); while (sc.hasNextLong()) { long aLong = sc.nextLong(); }
Scanner sc = new Scanner(new File("myNumbers"));
while (sc.hasNextLong()) {
    long aLong = sc.nextLong();
}

This code uses a Scanner to read lines from System#in. The Scanner uses the system property value of stdin.encoding as the Charset. Specifying the charset explicitly is important when reading from System.in, as it may differ from the default charset depending on the host environment or user configuration:

Scanner sc = new Scanner(System.in, System.getProperty("stdin.encoding")); while (sc.hasNextLine()) { String aLine = sc.nextLine(); }
Scanner sc = new Scanner(System.in, System.getProperty("stdin.encoding"));
while (sc.hasNextLine()) {
    String aLine = sc.nextLine();
}

The scanner can also use delimiters other than whitespace. This example reads several items in from a string:

String input = "1 fish 2 fish red fish blue fish"; Scanner s = new Scanner(input).useDelimiter("\s*fish\s*"); System.out.println(s.nextInt()); System.out.println(s.nextInt()); System.out.println(s.next()); System.out.println(s.next()); s.close();
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();

prints the following output:

1
    2
    red
    blue

The same output can be generated with this code, which uses a regular expression to parse all four tokens at once:

String input = "1 fish 2 fish red fish blue fish"; Scanner s = new Scanner(input); s.findInLine("(\d+) fish (\d+) fish (\w+) fish (\w+)"); MatchResult result = s.match(); for (int i=1; i<=result.groupCount(); i++) System.out.println(result.group(i)); s.close();
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input);
s.findInLine("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)");
MatchResult result = s.match();
for (int i=1; i<=result.groupCount(); i++)
    System.out.println(result.group(i));
s.close();

The default whitespace delimiter used by a scanner is as recognized by Character.isWhitespace(). The reset() method will reset the value of the scanner's delimiter to the default whitespace delimiter regardless of whether it was previously changed.

A scanning operation may block waiting for input.

The next and hasNext methods and their companion methods (such as nextInt and hasNextInt) first skip any input that matches the delimiter pattern, and then attempt to return the next token. Both hasNext() and next() methods may block waiting for further input. Whether a hasNext() method blocks has no connection to whether or not its associated next() method will block. The tokens method may also block waiting for input.

The findInLine(), findWithinHorizon(), skip(), and findAll() methods operate independently of the delimiter pattern. These methods will attempt to match the specified pattern with no regard to delimiters in the input and thus can be used in special circumstances where delimiters are not relevant. These methods may block waiting for more input.

When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.

Depending upon the type of delimiting pattern, empty tokens may be returned. For example, the pattern "\\s+" will return no empty tokens since it matches multiple instances of the delimiter. The delimiting pattern "\\s" could return empty tokens since it only passes one space at a time.

A scanner can read text from any object which implements the java.lang.Readable interface. If an invocation of the underlying readable's read() method throws an java.io.IOException then the scanner assumes that the end of the input has been reached. The most recent IOException thrown by the underlying readable can be retrieved via the ioException method.

When a Scanner is closed, it will close its input source if the source implements the java.io.Closeable interface.

A Scanner is not safe for multithreaded use without external synchronization.

Unless otherwise mentioned, passing a null parameter into any method of a Scanner will cause a NullPointerException to be thrown.

A scanner will default to interpreting numbers as decimal unless a different radix has been set by using the useRadix method. The reset method will reset the value of the scanner's radix to 10 regardless of whether it was previously changed.

Localized numbers

An instance of this class is capable of scanning numbers in the standard formats as well as in the formats of the scanner's locale. A scanner's initial locale is the value returned by the Locale.getDefault(Locale.Category.FORMAT) method; it may be changed via the useLocale() method. The reset method will reset the value of the scanner's locale to the initial locale regardless of whether it was previously changed.

The localized formats are defined in terms of the following parameters, which for a particular locale are taken from that locale's DecimalFormat object, df, and its DecimalFormatSymbols object, dfs.

LocalGroupSeparator  
The character used to separate thousands groups, i.e., dfs.getGroupingSeparator()
LocalDecimalSeparator  
The character used for the decimal point, i.e., dfs.getDecimalSeparator()
LocalPositivePrefix  
The string that appears before a positive number (may be empty), i.e., df.getPositivePrefix()
LocalPositiveSuffix  
The string that appears after a positive number (may be empty), i.e., df.getPositiveSuffix()
LocalNegativePrefix  
The string that appears before a negative number (may be empty), i.e., df.getNegativePrefix()
LocalNegativeSuffix  
The string that appears after a negative number (may be empty), i.e., df.getNegativeSuffix()
LocalNaN  
The string that represents not-a-number for floating-point values, i.e., dfs.getNaN()
LocalInfinity  
The string that represents infinity for floating-point values, i.e., dfs.getInfinity()

Number syntax

The strings that can be parsed as numbers by an instance of this class are specified in terms of the following regular-expression grammar, where Rmax is the highest digit in the radix being used (for example, Rmax is 9 in base 10).

NonAsciiDigit:
A non-ASCII character c for which Character.isDigit(c) returns true
Non0Digit:
[1-Rmax] | NonASCIIDigit
Digit:
[0-Rmax] | NonASCIIDigit
GroupedNumeral:
( Non0Digit Digit? Digit?
    ( LocalGroupSeparator Digit Digit Digit)+ )
Numeral:
( ( Digit+ ) | GroupedNumeral)
Integer:
( [-+]? ( Numeral) )
| LocalPositivePrefix Numeral LocalPositiveSuffix
| LocalNegativePrefix Numeral LocalNegativeSuffix
DecimalNumeral:
Numeral
| Numeral LocalDecimalSeparator Digit*
| LocalDecimalSeparator Digit+
Exponent:
( [eE] [+-]? Digit+ )
Decimal:
( [-+]? DecimalNumeral Exponent? )
| LocalPositivePrefix DecimalNumeral LocalPositiveSuffix Exponent?
| LocalNegativePrefix DecimalNumeral LocalNegativeSuffix Exponent?
HexFloat:
[-+]? 0[xX][0-9a-fA-F]*\.[0-9a-fA-F]+ ([pP][-+]?[0-9]+)?
NonNumber:
NaN | LocalNan| Infinity | LocalInfinity
SignedNonNumber:
( [-+]? NonNumber)
| LocalPositivePrefix NonNumber LocalPositiveSuffix
| LocalNegativePrefix NonNumber LocalNegativeSuffix
Float:
Decimal | HexFloat | SignedNonNumber

Whitespace is not significant in the above regular expressions.

Since
1.5

Nested and Inner Type Summary

Modifier and TypeClass and Description
pack-priv class
private static class
Scanner.PatternLRUCache

Small LRU cache of Patterns.

pack-priv class

Field Summary

Modifier and TypeField and Description
private static final String
private static volatile Pattern
boolPattern

Fields and an accessor method to match booleans

private CharBuffer
private static final int
private boolean
private Pattern
private String
private int
private Pattern
private static final String
private static final Pattern
private Pattern
floatPattern

Fields and methods to match floats and doubles

private String
groupSeparator

Locale dependent values used to scan numbers

private Pattern
private int
private String
private String
private Pattern
integerPattern

Fields and methods to match bytes, shorts, ints, and longs

private IOException
private static final String
private static final String
private static volatile Pattern
private Locale
private final Matcher
private boolean
pack-priv int
private String
private boolean
private String
private String
private static final String
private static final Pattern
private final Scanner.PatternLRUCache
private int
private String
private String
private int
private int
private static volatile Pattern
separatorPattern

Fields and an accessor method to match line separators

private static final int
private boolean
private Readable
private boolean
private Object
private static final Pattern

Constructor Summary

AccessConstructor and Description
private
Scanner(Readable
A character source implementing the Readable interface
source
,
Pattern
A delimiting pattern
pattern
)

Constructs a Scanner that returns values scanned from the specified source delimited by the specified pattern.

public
Scanner(Readable
A character source implementing the Readable interface
source
)

Constructs a new Scanner that produces values scanned from the specified source.

public
Scanner(InputStream
An input stream to be scanned
source
)

Constructs a new Scanner that produces values scanned from the specified input stream.

public
Scanner(InputStream
An input stream to be scanned
source
,
String
The encoding type used to convert bytes from the stream into characters to be scanned
charsetName
)

Constructs a new Scanner that produces values scanned from the specified input stream.

public
Scanner(InputStream
an input stream to be scanned
source
,
Charset
the charset used to convert bytes from the file into characters to be scanned
charset
)

Constructs a new Scanner that produces values scanned from the specified input stream.

public
Scanner(File
A file to be scanned
source
)

Constructs a new Scanner that produces values scanned from the specified file.

public
Scanner(File
A file to be scanned
source
,
String
The encoding type used to convert bytes from the file into characters to be scanned
charsetName
)

Constructs a new Scanner that produces values scanned from the specified file.

public
Scanner(File
A file to be scanned
source
,
Charset
The charset used to convert bytes from the file into characters to be scanned
charset
)

Constructs a new Scanner that produces values scanned from the specified file.

private
public
Scanner(Path
the path to the file to be scanned
source
)

Constructs a new Scanner that produces values scanned from the specified file.

public
Scanner(Path
the path to the file to be scanned
source
,
String
The encoding type used to convert bytes from the file into characters to be scanned
charsetName
)

Constructs a new Scanner that produces values scanned from the specified file.

public
Scanner(Path
the path to the file to be scanned
source
,
Charset
the charset used to convert bytes from the file into characters to be scanned
charset
)

Constructs a new Scanner that produces values scanned from the specified file.

public
Scanner(String
A string to scan
source
)

Constructs a new Scanner that produces values scanned from the specified string.

public
Scanner(ReadableByteChannel
A channel to scan
source
)

Constructs a new Scanner that produces values scanned from the specified channel.

public
Scanner(ReadableByteChannel
A channel to scan
source
,
String
The encoding type used to convert bytes from the channel into characters to be scanned
charsetName
)

Constructs a new Scanner that produces values scanned from the specified channel.

public
Scanner(ReadableByteChannel
a channel to scan
source
,
Charset
the encoding type used to convert bytes from the channel into characters to be scanned
charset
)

Constructs a new Scanner that produces values scanned from the specified channel.

Method Summary

Modifier and TypeMethod and Description
private static Pattern
private void
private String
private void
private void
private void
public void
close()

Implements java.io.Closeable.close.

Closes this scanner.

private Pattern
public Pattern

Returns:

this scanner's delimiting pattern.
delimiter
()

Returns the Pattern this Scanner is currently using to match delimiters.

private void
public Stream<MatchResult>

Returns:

a sequential stream of match results
findAll
(Pattern
the pattern to be matched
pattern
)

Returns a stream of match results from this scanner.

public Stream<MatchResult>

Returns:

a sequential stream of match results
findAll
(String
the pattern string
patString
)

Returns a stream of match results that match the provided pattern string.

public String

Returns:

the text that matched the specified pattern
findInLine
(String
a string specifying the pattern to search for
pattern
)

Attempts to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters.

public String

Returns:

the text that matched the specified pattern
findInLine
(Pattern
the pattern to scan for
pattern
)

Attempts to find the next occurrence of the specified pattern ignoring delimiters.

private boolean
findPatternInBuffer(Pattern pattern, int horizon)

public String

Returns:

the text that matched the specified pattern
findWithinHorizon
(String
a string specifying the pattern to search for
pattern
,
int
the search horizon
horizon
)

Attempts to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters.

public String

Returns:

the text that matched the specified pattern
findWithinHorizon
(Pattern
the pattern to scan for
pattern
,
int
the search horizon
horizon
)

Attempts to find the next occurrence of the specified pattern.

private Pattern
private String
private String
public boolean

Returns:

true if and only if this scanner has another token
hasNext
()

Implements java.util.Iterator.hasNext.

Returns true if this scanner has another token in its input.

public boolean

Returns:

true if and only if this scanner has another token matching the specified pattern
hasNext
(String
a string specifying the pattern to scan
pattern
)

Returns true if the next token matches the pattern constructed from the specified string.

public boolean

Returns:

true if and only if this scanner has another token matching the specified pattern
hasNext
(Pattern
the pattern to scan for
pattern
)

Returns true if the next complete token matches the specified pattern.

public boolean

Returns:

true if and only if this scanner's next token is a valid BigDecimal
hasNextBigDecimal
()

Returns true if the next token in this scanner's input can be interpreted as a BigDecimal using the nextBigDecimal method.

public boolean

Returns:

true if and only if this scanner's next token is a valid BigInteger
hasNextBigInteger
()

Returns true if the next token in this scanner's input can be interpreted as a BigInteger in the default radix using the nextBigInteger method.

public boolean

Returns:

true if and only if this scanner's next token is a valid BigInteger
hasNextBigInteger
(int
the radix used to interpret the token as an integer
radix
)

Returns true if the next token in this scanner's input can be interpreted as a BigInteger in the specified radix using the nextBigInteger method.

public boolean

Returns:

true if and only if this scanner's next token is a valid boolean value
hasNextBoolean
()

Returns true if the next token in this scanner's input can be interpreted as a boolean value using a case insensitive pattern created from the string "true|false".

public boolean

Returns:

true if and only if this scanner's next token is a valid byte value
hasNextByte
()

Returns true if the next token in this scanner's input can be interpreted as a byte value in the default radix using the nextByte method.

public boolean

Returns:

true if and only if this scanner's next token is a valid byte value
hasNextByte
(int
the radix used to interpret the token as a byte value
radix
)

Returns true if the next token in this scanner's input can be interpreted as a byte value in the specified radix using the nextByte method.

public boolean

Returns:

true if and only if this scanner's next token is a valid double value
hasNextDouble
()

Returns true if the next token in this scanner's input can be interpreted as a double value using the nextDouble method.

public boolean

Returns:

true if and only if this scanner's next token is a valid float value
hasNextFloat
()

Returns true if the next token in this scanner's input can be interpreted as a float value using the nextFloat method.

public boolean

Returns:

true if and only if this scanner's next token is a valid int value
hasNextInt
()

Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt method.

public boolean

Returns:

true if and only if this scanner's next token is a valid int value
hasNextInt
(int
the radix used to interpret the token as an int value
radix
)

Returns true if the next token in this scanner's input can be interpreted as an int value in the specified radix using the nextInt method.

public boolean

Returns:

true if there is a line separator in the remaining input or if the input has other remaining characters
hasNextLine
()

Returns true if there is another line in the input of this scanner.

public boolean

Returns:

true if and only if this scanner's next token is a valid long value
hasNextLong
()

Returns true if the next token in this scanner's input can be interpreted as a long value in the default radix using the nextLong method.

public boolean

Returns:

true if and only if this scanner's next token is a valid long value
hasNextLong
(int
the radix used to interpret the token as a long value
radix
)

Returns true if the next token in this scanner's input can be interpreted as a long value in the specified radix using the nextLong method.

public boolean

Returns:

true if and only if this scanner's next token is a valid short value in the default radix
hasNextShort
()

Returns true if the next token in this scanner's input can be interpreted as a short value in the default radix using the nextShort method.

public boolean

Returns:

true if and only if this scanner's next token is a valid short value in the specified radix
hasNextShort
(int
the radix used to interpret the token as a short value
radix
)

Returns true if the next token in this scanner's input can be interpreted as a short value in the specified radix using the nextShort method.

private boolean
private Pattern
public IOException

Returns:

the last exception thrown by this scanner's readable
ioException
()

Returns the IOException last thrown by this Scanner's underlying Readable.

private static Pattern
public Locale

Returns:

this scanner's locale
locale
()

Returns this scanner's locale.

private static Readable
makeReadable(Path source, Charset charset)

private static Readable
makeReadable(InputStream source, Charset charset)

private static Readable
private static Readable
private static Readable
private boolean
public MatchResult

Returns:

a match result for the last match operation
match
()

Returns the match result of the last scanning operation performed by this scanner.

private boolean
public String

Returns:

the next token
next
()

Implements java.util.Iterator.next.

Finds and returns the next complete token from this scanner.

public String

Returns:

the next token
next
(String
a string specifying the pattern to scan
pattern
)

Returns the next token if it matches the pattern constructed from the specified string.

public String

Returns:

the next token
next
(Pattern
the pattern to scan for
pattern
)

Returns the next token if it matches the specified pattern.

public BigDecimal

Returns:

the BigDecimal scanned from the input
nextBigDecimal
()

Scans the next token of the input as a BigDecimal.

public BigInteger

Returns:

the BigInteger scanned from the input
nextBigInteger
()

Scans the next token of the input as a BigInteger.

public BigInteger

Returns:

the BigInteger scanned from the input
nextBigInteger
(int
the radix used to interpret the token
radix
)

Scans the next token of the input as a BigInteger.

public boolean

Returns:

the boolean scanned from the input
nextBoolean
()

Scans the next token of the input into a boolean value and returns that value.

public byte

Returns:

the byte scanned from the input
nextByte
()

Scans the next token of the input as a byte.

public byte

Returns:

the byte scanned from the input
nextByte
(int
the radix used to interpret the token as a byte value
radix
)

Scans the next token of the input as a byte.

public double

Returns:

the double scanned from the input
nextDouble
()

Scans the next token of the input as a double.

public float

Returns:

the float scanned from the input
nextFloat
()

Scans the next token of the input as a float.

public int

Returns:

the int scanned from the input
nextInt
()

Scans the next token of the input as an int.

public int

Returns:

the int scanned from the input
nextInt
(int
the radix used to interpret the token as an int value
radix
)

Scans the next token of the input as an int.

public String

Returns:

the line that was skipped
nextLine
()

Advances this scanner past the current line and returns the input that was skipped.

public long

Returns:

the long scanned from the input
nextLong
()

Scans the next token of the input as a long.

public long

Returns:

the long scanned from the input
nextLong
(int
the radix used to interpret the token as an int value
radix
)

Scans the next token of the input as a long.

public short

Returns:

the short scanned from the input
nextShort
()

Scans the next token of the input as a short.

public short

Returns:

the short scanned from the input
nextShort
(int
the radix used to interpret the token as a short value
radix
)

Scans the next token of the input as a short.

private String
processFloatToken(String token)

The float token must be stripped of prefixes, group separators, and suffixes, non ascii digits must be converted into ascii digits before parseFloat will accept it.

private String
processIntegerToken(String token)

The integer token must be stripped of prefixes, group separators, and suffixes, non ascii digits must be converted into ascii digits before parse will accept it.

public int

Returns:

the default radix of this scanner
radix
()

Returns this scanner's default radix.

private void
public void
remove()

Overrides default java.util.Iterator.remove.

The remove operation is not supported by this implementation of Iterator.

public Scanner

Returns:

this scanner
reset
()

Resets this scanner.

private void
private boolean
revertState(boolean b)

private void
private static Pattern
private void
setRadix(int radix)

public Scanner

Returns:

this scanner
skip
(Pattern
the pattern to skip over
pattern
)

Skips input that matches the specified pattern, ignoring delimiters.

public Scanner

Returns:

this scanner
skip
(String
a string specifying the pattern to skip over
pattern
)

Skips input that matches a pattern constructed from the specified string.

private void
private static Charset
toCharset(String csn)

Returns a charset object for the given charset name.

private static CharsetDecoder
toDecoder(String charsetName)

public Stream<String>

Returns:

a sequential stream of token strings
tokens
()

Returns a stream of delimiter-separated tokens from this scanner.

public String

Returns:

The string representation of this scanner
toString
()

Overrides java.lang.Object.toString.

Returns the string representation of this Scanner.

private void
public Scanner

Returns:

this scanner
useDelimiter
(Pattern
A delimiting pattern
pattern
)

Sets this scanner's delimiting pattern to the specified pattern.

public Scanner

Returns:

this scanner
useDelimiter
(String
A string specifying a delimiting pattern
pattern
)

Sets this scanner's delimiting pattern to a pattern constructed from the specified String.

public Scanner

Returns:

this scanner
useLocale
(Locale
A string specifying the locale to use
locale
)

Sets this scanner's locale to the specified locale.

public Scanner

Returns:

this scanner
useRadix
(int
The radix to use when scanning numbers
radix
)

Sets this scanner's default radix to the specified radix.

private void
Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAllwaitwaitwait