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.     } 
posted @ 2014-03-16 23:41  brave-sailor  阅读(1278)  评论(0编辑  收藏  举报