JDK1.7 API -- Scanner

本文详细介绍了 Java 中 Scanner 类的功能及使用方法,包括如何利用正则表达式解析不同数据类型,构造方法、成员方法的说明,以及注意事项等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



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




原文:
java.util

Class Scanner

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 theuseRadix(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 TypeMethod and Description
    voidclose()
    Closes this scanner.
    Patterndelimiter()
    Returns the Pattern this Scanner is currently using to match delimiters.
    StringfindInLine(Pattern pattern)
    Attempts to find the next occurrence of the specified pattern ignoring delimiters.
    StringfindInLine(String pattern)
    Attempts to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters.
    StringfindWithinHorizon(Pattern pattern, int horizon)
    Attempts to find the next occurrence of the specified pattern.
    StringfindWithinHorizon(String pattern, int horizon)
    Attempts to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters.
    booleanhasNext()
    Returns true if this scanner has another token in its input.
    booleanhasNext(Pattern pattern)
    Returns true if the next complete token matches the specified pattern.
    booleanhasNext(String pattern)
    Returns true if the next token matches the pattern constructed from the specified string.
    booleanhasNextBigDecimal()
    Returns true if the next token in this scanner's input can be interpreted as aBigDecimal using the nextBigDecimal() method.
    booleanhasNextBigInteger()
    Returns true if the next token in this scanner's input can be interpreted as aBigInteger in the default radix using the nextBigInteger() method.
    booleanhasNextBigInteger(int radix)
    Returns true if the next token in this scanner's input can be interpreted as aBigInteger in the specified radix using the nextBigInteger() method.
    booleanhasNextBoolean()
    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".
    booleanhasNextByte()
    Returns true if the next token in this scanner's input can be interpreted as a byte value in the default radix using thenextByte() method.
    booleanhasNextByte(int radix)
    Returns true if the next token in this scanner's input can be interpreted as a byte value in the specified radix using thenextByte() method.
    booleanhasNextDouble()
    Returns true if the next token in this scanner's input can be interpreted as a double value using thenextDouble() method.
    booleanhasNextFloat()
    Returns true if the next token in this scanner's input can be interpreted as a float value using thenextFloat() method.
    booleanhasNextInt()
    Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using thenextInt() method.
    booleanhasNextInt(int radix)
    Returns true if the next token in this scanner's input can be interpreted as an int value in the specified radix using thenextInt() method.
    booleanhasNextLine()
    Returns true if there is another line in the input of this scanner.
    booleanhasNextLong()
    Returns true if the next token in this scanner's input can be interpreted as a long value in the default radix using thenextLong() method.
    booleanhasNextLong(int radix)
    Returns true if the next token in this scanner's input can be interpreted as a long value in the specified radix using thenextLong() method.
    booleanhasNextShort()
    Returns true if the next token in this scanner's input can be interpreted as a short value in the default radix using thenextShort() method.
    booleanhasNextShort(int radix)
    Returns true if the next token in this scanner's input can be interpreted as a short value in the specified radix using thenextShort() method.
    IOExceptionioException()
    Returns the IOException last thrown by this Scanner's underlyingReadable.
    Localelocale()
    Returns this scanner's locale.
    MatchResultmatch()
    Returns the match result of the last scanning operation performed by this scanner.
    Stringnext()
    Finds and returns the next complete token from this scanner.
    Stringnext(Pattern pattern)
    Returns the next token if it matches the specified pattern.
    Stringnext(String pattern)
    Returns the next token if it matches the pattern constructed from the specified string.
    BigDecimalnextBigDecimal()
    Scans the next token of the input as a BigDecimal.
    BigIntegernextBigInteger()
    Scans the next token of the input as a BigInteger.
    BigIntegernextBigInteger(int radix)
    Scans the next token of the input as a BigInteger.
    booleannextBoolean()
    Scans the next token of the input into a boolean value and returns that value.
    bytenextByte()
    Scans the next token of the input as a byte.
    bytenextByte(int radix)
    Scans the next token of the input as a byte.
    doublenextDouble()
    Scans the next token of the input as a double.
    floatnextFloat()
    Scans the next token of the input as a float.
    intnextInt()
    Scans the next token of the input as an int.
    intnextInt(int radix)
    Scans the next token of the input as an int.
    StringnextLine()
    Advances this scanner past the current line and returns the input that was skipped.
    longnextLong()
    Scans the next token of the input as a long.
    longnextLong(int radix)
    Scans the next token of the input as a long.
    shortnextShort()
    Scans the next token of the input as a short.
    shortnextShort(int radix)
    Scans the next token of the input as a short.
    intradix()
    Returns this scanner's default radix.
    voidremove()
    The remove operation is not supported by this implementation of Iterator.
    Scannerreset()
    Resets this scanner.
    Scannerskip(Pattern pattern)
    Skips input that matches the specified pattern, ignoring delimiters.
    Scannerskip(String pattern)
    Skips input that matches a pattern constructed from the specified string.
    StringtoString()
    Returns the string representation of this Scanner.
    ScanneruseDelimiter(Pattern pattern)
    Sets this scanner's delimiting pattern to the specified pattern.
    ScanneruseDelimiter(String pattern)
    Sets this scanner's delimiting pattern to a pattern constructed from the specifiedString.
    ScanneruseLocale(Locale locale)
    Sets this scanner's locale to the specified locale.
    ScanneruseRadix(int radix)
    Sets this scanner's default radix to the specified radix.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值