Scanner是新增的一個簡易文本掃描器,在 JDK 5.0之前,是沒有的。查看最新在線文檔:
- public final class Scanner
- extends Object
- implements Iterator<String>, Closeable
可見,Scanner是沒有子類的。
在JDK API關於Scanner提供了比較多的構造方法與方法。那麼現在列出一些在平時工作中比較常用的方法,僅供大家參考:
構造方法:
- public Scanner(File source) throws FileNotFoundException
- public Scanner(String source)
- public Scanner(InputStream source) //用指定的輸入流來創建一個Scanner對象
方法:
- public void close() //關閉
- public Scanner useDelimiter(String pattern) //設置分隔模式 ,String可以用Pattern取代
- public boolean hasNext() //檢測輸入中,是否,還有單詞
- public String next() //讀取下一個單詞,默認把空格作爲分隔符
- public String nextLine() //讀行
- 註釋:從hasNext(),next()繁衍了大量的同名不同參方法,這裏不一一列出,感興趣的,可以查看API
以下一個綜合例子:
- package com.ringcentral.util;
- import java.util.*;
- import java.io.*;
- /**
- * author @dylan
- * date @2012-5-27
- */
- public class ScannerTest {
- public static void main(String[] args) {
- file_str(true);
- reg_str();
- }
- /**
- *
- * @param flag : boolean
- */
- public static void file_str(boolean flag){
- String text1= "last summber ,I went to the italy";
- //掃描本文件,url是文件的路徑
- String url = "E:\\Program Files\\C _ Code\\coreJava\\src\\com\\ringcentral\\util\\ScannerTest.java";
- File file_one = new File(url);
- Scanner sc= null;
- /*
- * 增加一個if語句,通過flag這個參數來決定使用那個構造方法。
- * flag = true :輸入結果爲本文件的內容。
- * flag = false :輸入結果爲 text1的值。
- */
- if(flag){
- try {
- sc =new Scanner(file_one);
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- }
- }else{
- sc=new Scanner(text1);
- }
- while(sc.hasNext())
- System.out.println(sc.nextLine());
- //記得要關閉
- sc.close();
- }
- public static void reg_str(){
- String text1= "last summber 23 ,I went to 555 the italy 4 ";
- //如果你只想輸入數字:23,555,4;可以設置分隔模式,把非數字進行過濾。
- Scanner sc = new Scanner(text1).useDelimiter("\\D\\s*");
- while(sc.hasNext()){
- System.out.println(sc.next());
- }
- sc.close();
- }
- }
- public static void input_str(){
- Scanner sc = new Scanner(System.in);
- System.out.println(sc.nextLine());
- sc.close();
- System.exit(0);
- }