java.util.Scanner的日常用法

Scanner是新增的一個簡易文本掃描器,在 JDK 5.0之前,是沒有的。查看最新在線文檔:

  1. public final class Scanner 
  2. extends Object 
  3. implements Iterator<String>, Closeable 

可見,Scanner是沒有子類的。

在JDK API關於Scanner提供了比較多的構造方法與方法。那麼現在列出一些在平時工作中比較常用的方法,僅供大家參考:

構造方法:

  1. public Scanner(File source) throws FileNotFoundException 
  2. public Scanner(String source) 
  3. public Scanner(InputStream source) //用指定的輸入流來創建一個Scanner對象

方法:

  1. public void close()    //關閉 
  2. public Scanner useDelimiter(String pattern) //設置分隔模式 ,String可以用Pattern取代
  3. public boolean hasNext() //檢測輸入中,是否,還有單詞
  4. public String next()   //讀取下一個單詞,默認把空格作爲分隔符
  5. public String nextLine()  //讀行 
  6. 註釋:從hasNext(),next()繁衍了大量的同名不同參方法,這裏不一一列出,感興趣的,可以查看API

以下一個綜合例子:

  1. package com.ringcentral.util; 
  2. import java.util.*; 
  3. import java.io.*; 
  4. /** 
  5.  * author @dylan 
  6.  * date   @2012-5-27 
  7.  */ 
  8. public class ScannerTest { 
  9.     public static void main(String[] args) { 
  10.         file_str(true); 
  11.         reg_str(); 
  12.     } 
  13.     /** 
  14.      *  
  15.      * @param flag : boolean  
  16.      */ 
  17.     public static void file_str(boolean flag){ 
  18.         String text1= "last summber ,I went to the italy"
  19.         //掃描本文件,url是文件的路徑 
  20.         String url = "E:\\Program Files\\C _ Code\\coreJava\\src\\com\\ringcentral\\util\\ScannerTest.java"
  21.         File file_one = new File(url); 
  22.         Scanner sc= null
  23.         /* 
  24.          * 增加一個if語句,通過flag這個參數來決定使用那個構造方法。 
  25.          * flag = true :輸入結果爲本文件的內容。 
  26.          * flag = false :輸入結果爲 text1的值。 
  27.          */ 
  28.         if(flag){ 
  29.             try { 
  30.                 sc =new Scanner(file_one); 
  31.             } catch (FileNotFoundException e) { 
  32.                 e.printStackTrace(); 
  33.             } 
  34.         }else
  35.             sc=new Scanner(text1); 
  36.         } 
  37.         while(sc.hasNext()) 
  38.             System.out.println(sc.nextLine()); 
  39.         //記得要關閉 
  40.         sc.close(); 
  41.     } 
  42.     public static void reg_str(){ 
  43.         String text1= "last summber 23 ,I went to 555 the italy 4 "
  44.         //如果你只想輸入數字:23,555,4;可以設置分隔模式,把非數字進行過濾。 
  45.         Scanner sc = new Scanner(text1).useDelimiter("\\D\\s*"); 
  46.         while(sc.hasNext()){ 
  47.                 System.out.println(sc.next());   
  48.         } 
  49.         sc.close(); 
  50.     } 
  51.  
  52.  
    1. public static void input_str(){ 
    2.         Scanner sc = new Scanner(System.in); 
    3.         System.out.println(sc.nextLine()); 
    4.         sc.close(); 
    5.         System.exit(0); 
    6.     } 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章