Class Scanner
java.util.Scanner
Scanner所实现的接口:
Closeable, AutoCloseable, Iterator<String>
public final class Scanner extends Object implements Iterator<String>, Closeable
这是一个可以使用正则表达式来解析基本数据类型和字符串的简单的文本扫描器。
Scanner将输入数据用分隔符分隔开来,默认通过空格来分隔输入数据。被分隔出来的各个数据段可以通过调用多种多样的next()方
法被转换成不同的数据类型。
例如,下面的代码允许用户从标准输入中读入整数:
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
再如,下面的代码可以从文件中读入长整形数据:
Scanner sc = new Scanner(new File("myNumbers"));
while (sc.hasNextLong()) {
long aLong = sc.nextLong();
}
Scanner也可以把除空格符以外的字符做为分隔符,下面的例子从一个字符串中读入了多项数据:
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();
输出结果为:
1
2
red
blue
也可以使用正则表达式一次性地将数据分隔完毕,如:
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();
Scanner 通过Character.isWhitespace()方法来判断一个字符是否是默认的空格分隔符。Reset()方法会将Scanner默认的分隔符重
设为空格,而不管之前是否曾经改变过Scanner的默认分隔符.
扫描操作可能为因为等待输入而发生阻塞。
Next()方法、hasNext()方法和它们对应的基础数据类型版本的方法(如nextInt(),hasNextInt()等等)首先会跳过符合指定格式的输
入数据,然后会将路过的部分返回。Next()方法和hasNext()方法都可能会因为等待输入而发生阻塞。但是,next()方法会不会阻塞
跟hasNext()方法会不会阻塞是没有任何关系的。
findInLine()方法、findWithinHorizon()方法和skip()方法忽略默认的分隔符。这些方法会尝试着去匹配参数中指定的格式而忽略
默认分隔符的影响,因此可以在某些需要特定格式的情况下使用。这几个方法都可能为因为等待输入而发生阻塞。
当一个Scanner抛出一个InputMismatchException时,Scanner会跳过发生异常的数据段。这些被路过的数据段可以通过一些方法来获
取。
Scanner有可能会返回一个空的数据段。例如,指定"\\s+"格式时,如果有多个数据段符合这个格式,那Scanner将返回空。
Scanner可以从任何实现了Readable接口的对象中读取数据。如果实现了Readable接口的这些对象调用了read方法,并且抛出了
IOException异常,那么Scanner会认为已经读到了数据结尾。我们可以通过ioException()方法来获取最近抛出的IOException异常
。
当一个Scanner被关闭时,它也会关闭与它相关联的数据输入源。
Scanner不是线程安全的类。
向Scanner类的任何方法传递null引用都会引发 NullPointerException 异常。
Scanner默认会用10进制的方式来处理数字,除非使用了 useRadix(int)方法来指定进制。reset()方法会将Scanner的进制重设为
10.
构造方法:
Scanner(File source)
构造一个可以从指定文件中读取数据的Scanner.
Scanner(File source, String charsetName)
构造一个可以从指定文件中读取数据的Scanner.(使用指定的字符集)
Scanner(InputStream source)
构造一个从指定的输入流读取数据的Scanner.
Scanner(InputStream source, String charsetName)
构造一个从指定的输入流读取数据的Scanner.(使用指定的字符集)
Scanner(Path source)
构造一个可以从指定路径的文件中读取数据的Scanner.
Scanner(Path source, String charsetName)
构造一个可以从指定路径的文件中读取数据的Scanner.(使用指定的字符集)
Scanner(Readable source)
构造一个从指定资源中读取数据的Scanner.
Scanner(ReadableByteChannel source)
构造一个从指定频道中读取数据的Scanner.
Scanner(ReadableByteChannel source, String charsetName)
构造一个从指定频道中读取数据的Scanner.(使用指定的字符集)
Scanner(String source)
构造一个从指定字符串对象中读取数据的Scanner.
成员方法:
void close()
关闭Scanner.
Pattern delimiter()
返回Scanner当前正在使用的匹配格式。
String findInLine(Pattern pattern)
用指定的格式读取数据。
String findInLine(String pattern)
用指定的格式读取数据。
boolean hasNext()
如果输入中还有数据段,则返回真。
boolean hasNext(Pattern pattern)
如果输入中还有满足指定格式的数据段,则返回真。
boolean hasNext(String pattern)
如果输入中还有满足指定格式的数据段,则返回真。
boolean hasNextBigDecimal()
如果下一个数据段可以用nextBigDecimal()转换成长小数,则返回真。
boolean hasNextBigInteger()
如果下一个数据段可以用nextBigInteger()方法转换成大整数(使用默认的进制),则返回真。
boolean hasNextBigInteger(int radix)
如果下一个数据段可以用nextBigInteger()方法转换成大整数(使用指定的进制),则返回真。
boolean hasNextBoolean()
如果下一个数据段可以被转换成boolean类型的数据,返回真。
boolean hasNextByte()
如果下一个数据段可以被转换成字节类型(使用默认进制),返回真。
boolean hasNextByte(int radix)
如果下一个数据段可以被转换成字节类型(使用进制进制),返回真。
boolean hasNextDouble()
如果下一个数据段可以通过调用nextDouble()方法转换成double类型数据,返回真。
boolean hasNextFloat()
如果下一个数据段可以通过调用nextFloat()方法转换成Float类型数据,返回真。
boolean hasNextInt()
如果下一个数据段可以通过调用nextInt()方法转换成int类型数据(使用默认进制),返回真。
boolean hasNextInt(int radix)
如果下一个数据段可以通过调用nextInt()方法转换成int类型数据(使用指定进制),返回真。
boolean hasNextLine()
如果还有下一行数据,返回真。
boolean hasNextLong()
如果下一个数据段可以通过调用nextLong()方法转换成long类型数据(使用默认进制),返回真。
boolean hasNextLong(int radix)
如果下一个数据段可以通过调用nextLong()方法转换成long类型数据(使用指定进制),返回真。
boolean hasNextShort()
如果下一个数据段可以通过调用nextShort()方法转换成short类型数据(使用默认进制),返回真。
boolean hasNextShort(int radix)
如果下一个数据段可以通过调用nextShort()方法转换成short类型数据(使用指定进制),返回真。\
IOException ioException()
返回数据源最近抛出的IOException异常。
Locale locale()
返回Scanner当前的位置。
MatchResult match()
返回通过最近指定的格式来匹配数据的结果。
String next()
返回下一个数据段。
String next(Pattern pattern)
返回下一个使用指定格式分割的数据段。
BigDecimal nextBigDecimal()
将下一个数据段转换成长小数。
BigInteger nextBigInteger()
将下一个数据段转换成大整数。
BigInteger nextBigInteger(int radix)
将下一个数据段转换成长小数。使用指定进制。
boolean nextBoolean()
将下一个数据段转换成boolean类型的数据。
byte nextByte()
将下一个数据段转换成字节类型的数据。使用默认进制。
byte nextByte(int radix)
将下一个数据段转换成字节类型的数据。使用指定的进制。
double nextDouble()
将下一个数据段转换成double类型的数据。
float nextFloat()
将下一个数据段转换成float类型的数据。
int nextInt()
将下一个数据段转换成int类型的数据。使用默认进制。
int nextInt(int radix)
将下一个数据段转换成int类型的数据。使用指定进制。
String nextLine()
跳过当前行,并将路过的数据返回。
long nextLong()
将下一个数据段转换成long类型的数据。使用默认进制。
long nextLong(int radix)
将下一个数据段转换成int类型的数据。使用指定进制。
short nextShort()
将下一个数据段转换成short类型的数据。使用默认进制。
short nextShort(int radix)
将下一个数据段转换成short类型的数据。使用指定进制。
int radix()
设置Scanner的进制。
void remove()
这个类的迭代器不支持remove方法。
Scanner reset()
重设Scanner.
Scanner skip(Pattern pattern)
跳过指定格式的数据。
Scanner skip(String pattern)
跳过指定格式的数据。
String toString()
返回一个能描述这个Scanner的字符串。
Scanner useDelimiter(Pattern pattern)
设定Scanner使用指定的格式分隔数据。
Scanner useDelimiter(String pattern)
设定Scanner使用指定的格式分隔数据。
Scanner useLocale(Locale locale)
Sets this scanner's locale to the specified locale.
Scanner useRadix(int radix)
改变Scanner的默认进制。
从java.lang.Object类中继承的方法:
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
原文:
-
All Implemented Interfaces:
-
Closeable, AutoCloseable, Iterator< String>
public final class
Scannerextends Objectimplements Iterator< String>, CloseableA 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 variousnext methods.
For example, this code allows a user to read a number from System.in:
Scanner sc = new Scanner(System.in); int i = sc.nextInt();
As another example, this code allows long
types to be assigned from entries in a filemyNumbers
:
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 in from a string:
String input = "1 fish 2 fish red fish blue fish"; Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*"); System.out.println(s.nextInt()); System.out.println(s.nextInt()); System.out.println(s.next()); System.out.println(s.next()); s.close();
prints the following output:
1 2 red blue
The same output can be generated with this code, which uses a regular expression to parse all four tokens at once:
String input = "1 fish 2 fish red fish blue fish"; Scanner s = new Scanner(input); s.findInLine("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)"); MatchResult result = s.match(); for (int i=1; i<=result.groupCount(); i++) System.out.println(result.group(i)); s.close();
The default whitespace delimiter used by a scanner is as recognized byCharacter
.isWhitespace
. Thereset()
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 primitive-type companion methods (such asnextInt()
and hasNextInt()
) first skip any input that matches the delimiter pattern, and then attempt to return the next token. BothhasNext and next methods may block waiting for further input. Whether ahasNext method blocks has no connection to whether or not its associatednext method will block.
The findInLine(java.lang.String)
, findWithinHorizon(java.lang.String, int)
, and skip(java.util.regex.Pattern)
methods operate independently of the delimiter pattern. These methods will attempt to match the specified pattern with no regard to delimiters in the input and thus can be used in special circumstances where delimiters are not relevant. These methods may block waiting for more input.
When a scanner throws an InputMismatchException
, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.
Depending upon the type of delimiting pattern, empty tokens may be returned. For example, the pattern"\\s+" will return no empty tokens since it matches multiple instances of the delimiter. The delimiting pattern"\\s" could return empty tokens since it only passes one space at a time.
A scanner can read text from any object which implements the Readable
interface. If an invocation of the underlying readable'sReadable.read(java.nio.CharBuffer)
method throws anIOException
then the scanner assumes that the end of the input has been reached. The most recentIOException 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 theCloseable
interface.
A Scanner
is not safe for multithreaded use without external synchronization.
Unless otherwise mentioned, passing a null
parameter into any method of aScanner
will cause a NullPointerException
to be thrown.
A scanner will default to interpreting numbers as decimal unless a different radix has been set by using the
useRadix(int)
method. The
reset()
method will reset the value of the scanner's radix to
10
regardless of whether it was previously changed.
Constructor Summary
Constructors
Constructor and Description |
Scanner(File source)
Constructs a new
Scanner that produces values scanned from the specified file.
|
Scanner(File source,String charsetName)
Constructs a new
Scanner that produces values scanned from the specified file.
|
Scanner(InputStream source)
Constructs a new
Scanner that produces values scanned from the specified input stream.
|
Scanner(InputStream source,String charsetName)
Constructs a new
Scanner that produces values scanned from the specified input stream.
|
Scanner(Path source)
Constructs a new
Scanner that produces values scanned from the specified file.
|
Scanner(Path source,String charsetName)
Constructs a new
Scanner that produces values scanned from the specified file.
|
Scanner(Readable source)
Constructs a new
Scanner that produces values scanned from the specified source.
|
Scanner(ReadableByteChannel source)
Constructs a new
Scanner that produces values scanned from the specified channel.
|
Scanner(ReadableByteChannel source,String charsetName)
Constructs a new
Scanner that produces values scanned from the specified channel.
|
Scanner(String source)
Constructs a new
Scanner that produces values scanned from the specified string.
|
-
Method Summary
Methods
Modifier and Type |
Method and Description |
void |
close()
Closes this scanner.
|
Pattern |
delimiter()
Returns the
Pattern this
Scanner is currently using to match delimiters.
|
String |
findInLine(Pattern pattern)
Attempts to find the next occurrence of the specified pattern ignoring delimiters.
|
String |
findInLine(String pattern)
Attempts to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters.
|
String |
findWithinHorizon(Pattern pattern, int horizon)
Attempts to find the next occurrence of the specified pattern.
|
String |
findWithinHorizon(String pattern, int horizon)
Attempts to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters.
|
boolean |
hasNext()
Returns true if this scanner has another token in its input.
|
boolean |
hasNext(Pattern pattern)
Returns true if the next complete token matches the specified pattern.
|
boolean |
hasNext(String pattern)
Returns true if the next token matches the pattern constructed from the specified string.
|
boolean |
hasNextBigDecimal()
Returns true if the next token in this scanner's input can be interpreted as a
BigDecimal using the
nextBigDecimal() method.
|
boolean |
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.
|
boolean |
hasNextBigInteger(int 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.
|
boolean |
hasNextBoolean()
Returns true if the next token in this scanner's input can be interpreted as a boolean value using a case insensitive pattern created from the string "true|false".
|
boolean |
hasNextByte()
Returns true if the next token in this scanner's input can be interpreted as a byte value in the default radix using the
nextByte() method.
|
boolean |
hasNextByte(int radix)
Returns true if the next token in this scanner's input can be interpreted as a byte value in the specified radix using the
nextByte() method.
|
boolean |
hasNextDouble()
Returns true if the next token in this scanner's input can be interpreted as a double value using the
nextDouble() method.
|
boolean |
hasNextFloat()
Returns true if the next token in this scanner's input can be interpreted as a float value using the
nextFloat() method.
|
boolean |
hasNextInt()
Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the
nextInt() method.
|
boolean |
hasNextInt(int radix)
Returns true if the next token in this scanner's input can be interpreted as an int value in the specified radix using the
nextInt() method.
|
boolean |
hasNextLine()
Returns true if there is another line in the input of this scanner.
|
boolean |
hasNextLong()
Returns true if the next token in this scanner's input can be interpreted as a long value in the default radix using the
nextLong() method.
|
boolean |
hasNextLong(int radix)
Returns true if the next token in this scanner's input can be interpreted as a long value in the specified radix using the
nextLong() method.
|
boolean |
hasNextShort()
Returns true if the next token in this scanner's input can be interpreted as a short value in the default radix using the
nextShort() method.
|
boolean |
hasNextShort(int radix)
Returns true if the next token in this scanner's input can be interpreted as a short value in the specified radix using the
nextShort() method.
|
IOException |
ioException()
Returns the
IOException last thrown by this
Scanner 's underlying
Readable .
|
Locale |
locale()
Returns this scanner's locale.
|
MatchResult |
match()
Returns the match result of the last scanning operation performed by this scanner.
|
String |
next()
Finds and returns the next complete token from this scanner.
|
String |
next(Pattern pattern)
Returns the next token if it matches the specified pattern.
|
String |
next(String pattern)
Returns the next token if it matches the pattern constructed from the specified string.
|
BigDecimal |
nextBigDecimal()
Scans the next token of the input as a
BigDecimal .
|
BigInteger |
nextBigInteger()
Scans the next token of the input as a
BigInteger .
|
BigInteger |
nextBigInteger(int radix)
Scans the next token of the input as a
BigInteger .
|
boolean |
nextBoolean()
Scans the next token of the input into a boolean value and returns that value.
|
byte |
nextByte()
Scans the next token of the input as a byte.
|
byte |
nextByte(int radix)
Scans the next token of the input as a byte.
|
double |
nextDouble()
Scans the next token of the input as a double.
|
float |
nextFloat()
Scans the next token of the input as a float.
|
int |
nextInt()
Scans the next token of the input as an int.
|
int |
nextInt(int radix)
Scans the next token of the input as an int.
|
String |
nextLine()
Advances this scanner past the current line and returns the input that was skipped.
|
long |
nextLong()
Scans the next token of the input as a long.
|
long |
nextLong(int radix)
Scans the next token of the input as a long.
|
short |
nextShort()
Scans the next token of the input as a short.
|
short |
nextShort(int radix)
Scans the next token of the input as a short.
|
int |
radix()
Returns this scanner's default radix.
|
void |
remove()
The remove operation is not supported by this implementation of
Iterator .
|
Scanner |
reset()
Resets this scanner.
|
Scanner |
skip(Pattern pattern)
Skips input that matches the specified pattern, ignoring delimiters.
|
Scanner |
skip(String pattern)
Skips input that matches a pattern constructed from the specified string.
|
String |
toString()
Returns the string representation of this
Scanner .
|
Scanner |
useDelimiter(Pattern pattern)
Sets this scanner's delimiting pattern to the specified pattern.
|
Scanner |
useDelimiter(String pattern)
Sets this scanner's delimiting pattern to a pattern constructed from the specified
String .
|
Scanner |
useLocale(Locale locale)
Sets this scanner's locale to the specified locale.
|
Scanner |
useRadix(int radix)
Sets this scanner's default radix to the specified radix.
|
-
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait