Scanner類的學習

java.util包

1)首先記住它的8中構造方法同PrintWriter類Scanner類同樣可以直接對文件進行操作

Scanner(File source)  構造一個新的 Scanner,它生成的值是從指定文件掃描的,底層平臺的默認字符集轉換成字符。 

Scanner(File source, String csn)指定字符集  。

  但如果用String的話是不能指定字符集的

Scanner(String source) 構造一個新的 Scanner,它生成的值是從指定字符串掃描的,Scanner的這個構造方法允許它能作爲掃描器。 

  注意同PrintWriter的區別,若想指定字符集就必須將目錄或文件轉換成File對象。不同於PrintWriter()的還有當以流作爲輸入對象時,他是可以指定字符集的

Scanner(InputStream source) 構造一個新的 Scanner,它生成的值是從指定的輸入流掃描的。 

Scanner(InputStream source, String charsetName) 構造一個新的 Scanner,它生成的值是從指定的輸入流掃描的。

 還有Scanner能夠將實現Readable,ReadableByteChannel接口的類作爲參數

Scanner(Readable source)  構造一個新的 Scanner,它生成的值是從指定源掃描的。 

Scanner(ReadableByteChannel source) 構造一個新的 Scanner,它生成的值是從指定信道掃描的。 

Scanner(ReadableByteChannel source, String csn) 構造一個新的 Scanner,它生成的值是從指定信道掃描的。

2)Scanner類實現了Iterator接口

所以它有boolean hasNext()方法

Object next()方法

void remove()方法

3)常用方法

1.useDelimiter()【useDelimiter使用定界符的意思】將Scanner類的分隔模式設置爲指定模式,這個方法讓Scanner對象成爲了掃描器(參見API)

例如:

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 
補充:

\s——代表任何空白字符

\S——代表任何非空白字符

以下代碼使用正則表達式同時解析所有的 4 個標記,並可以產生與上例相同的輸出結果:

     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();
補充:

\d——代表任何數字字符,即[0-9]

\D——代表任何非數字字符

\w——代表任何單字字符(字母a~z、A~Z、下劃線、0~9),即[a-zA-Z_0-9]

\W——代表任何非單字字符

下面的例子幫助你記住該段

import java.util.regex.Pattern; import java.util.regex.Matcher; public class RegexTest3 { public static void main(String[] args) {

String str ="We call this the live-code approach.These examples are available from three locations-they are "             +"on the CD that accompanies this book"; String  regex = "[a-zA-Z]+";  //根據單詞的特性準備一個正則表達式。 Pattern  pObj = Pattern.compile(regex); //1 匹配模式對象。 Matcher  mObj = pObj.matcher( str ); //2 將正則表達式轉換成一個匹配器 System.out.println("你給定的字符串如下: \n\"" + str + "\"");

System.out.println("\n以上字符串中包含的單詞分別如下:");

int counter = 0;

while( mObj.find()) {//3 查找 String word = mObj.group();//4 獲取 counter++;//計數 System.out.println("第" + counter + "單詞是: " + word ); //處理(顯示) }

} }

2.下面的方法和DataInputStream中的方法readXxx()類似

    nextXxx()從流中讀取一個Xxx並返回Xxx值。具體詳見API

發佈了18 篇原創文章 · 獲贊 13 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章