在JDK API关于Scanner提供了比较多的构造方法与方法。那么如今列出一些在平时工做中比较经常使用的方法,仅供你们参考: java
构造方法: url
- public Scanner(File source) throws FileNotFoundException
- public Scanner(String source)
- public Scanner(InputStream source) //用指定的输入流来建立一个Scanner对象
方法: spa
- public void close() //关闭
- public Scanner useDelimiter(String pattern) //设置分隔模式 ,String能够用Pattern取代
- public boolean hasNext() //检测输入中,是否,还有单词
- public String next() //读取下一个单词,默认把空格做为分隔符
- public String nextLine() //读行
- 注释:从hasNext(),next()繁衍了大量的同名不一样参方法,这里不一一列出,感兴趣的,能够查看API
如下一个综合例子: code
- 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);
- }
本文出自 “一米阳光” 博客,请务必保留此出处http://isunshine.blog.51cto.com/2298151/880038 对象