Java中的Scannner

java.util.Scanner是Java5的新特徵,主要功能是簡化文本掃描。這個類最實用的地方表現在獲取控制檯輸入,其他的功能都很雞肋,儘管Java API文檔中列舉了大量的API方法,但是都不怎麼地。

一、掃描控制檯輸入

這個例子是常常會用到,但是如果沒有Scanner,你寫寫就知道多難受了。
當通過new Scanner(System.in)創建一個Scanner,控制檯會一直等待輸入,直到敲回車鍵結束,把所輸入的內容傳給Scanner,作爲掃描對象。如果要獲取輸入的內容,則只需要調用Scanner的nextLine()方法即可。

/** 
* 掃描控制檯輸入 

* @author leizhimin 2009-7-24 11:24:47 
*/
 
public class TestScanner { 
        public static void main(String[] args) { 
                Scanner s = new Scanner(System.in); 
                System.out.println("請輸入字符串:"); 
                while (true) { 
                        String line = s.nextLine(); 
                        if (line.equals("exit")) break
                        System.out.println(">>>" + line); 
                } 
        } 
}



請輸入字符串: 
234 
>>>234 
wer 
>>>wer 
bye 
>>>bye 
exit 

Process finished with exit code 0



先寫這裏吧,有空再繼續完善。

二、如果說Scanner使用簡便,不如說Scanner的構造器支持多種方式,構建Scanner的對象很方便。

可以從字符串(Readable)、輸入流、文件等等來直接構建Scanner對象,有了Scanner了,就可以逐段(根據正則分隔式)來掃描整個文本,並對掃描後的結果做想要的處理。

三、Scanner默認使用空格作爲分割符來分隔文本,但允許你指定新的分隔符

使用默認的空格分隔符:
        public static void main(String[] args) throws FileNotFoundException { 
                Scanner s = new Scanner("123 asdf sd 45 789 sdf asdfl,sdf.sdfl,asdf    ......asdfkl    las"); 
//                s.useDelimiter(" |,|\\."); 
                while (s.hasNext()) { 
                        System.out.println(s.next()); 
                } 
        }



123 
asdf 
sd 
45 
789 
sdf 
asdfl,sdf.sdfl,asdf 
......asdfkl 
las 

Process finished with exit code 0



將註釋行去掉,使用空格或逗號或點號作爲分隔符,輸出結果如下:
123 
asdf 
sd 
45 
789 
sdf 
asdfl 
sdf 
sdfl 
asdf 







asdfkl 

las 

Process finished with exit code 0




四、一大堆API函數,實用的沒幾個

(很多API,註釋很讓人迷惑,幾乎毫無用處,這個類就這樣被糟蹋了,啓了很不錯的名字,實際上做的全是齷齪事)

下面這幾個相對實用:

delimiter() 
          返回此 Scanner 當前正在用於匹配分隔符的 Pattern。
hasNext() 
          判斷掃描器中當前掃描位置後是否還存在下一段。(原APIDoc的註釋很扯淡)
hasNextLine() 
          如果在此掃描器的輸入中存在另一行,則返回 true。
next() 
          查找並返回來自此掃描器的下一個完整標記。
nextLine() 
          此掃描器執行當前行,並返回跳過的輸入信息。



五、逐行掃描文件,並逐行輸出

看不到價值的掃描過程
        public static void main(String[] args) throws FileNotFoundException { 
                InputStream in = new FileInputStream(new File("C:\\AutoSubmit.java")); 
                Scanner s = new Scanner(in); 
                while(s.hasNextLine()){ 
                        System.out.println(s.nextLine()); 
                } 
        }
發佈了38 篇原創文章 · 獲贊 16 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章