| java.util.Scanner是Java5的新特征,主要功能是簡(jiǎn)化文本掃描。這個(gè)類最實(shí)用的地方表現(xiàn)在獲取控制臺(tái)輸入,其他的功能都很雞肋,盡管Java API文檔中列舉了大量的API方法,但是都不怎么地。 一、掃描控制臺(tái)輸入 這個(gè)例子是常常會(huì)用到,但是如果沒有Scanner,你寫寫就知道多難受了。 當(dāng)通過new Scanner(System.in)創(chuàng)建一個(gè)Scanner,控制臺(tái)會(huì)一直等待輸入,直到敲回車鍵結(jié)束,把所輸入的內(nèi)容傳給Scanner,作為掃描對(duì)象。如果要獲取輸入的內(nèi)容,則只需要調(diào)用Scanner的nextLine()方法即可。 /**  * 掃描控制臺(tái)輸入 * * @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("請(qǐng)輸入字符串:"); while (true) { String line = s.nextLine(); if (line.equals("exit")) break; System.out.println(">>>" + line); } } } 請(qǐng)輸入字符串:  234 >>>234 wer >>>wer bye >>>bye exit Process finished with exit code 0 先寫這里吧,有空再繼續(xù)完善。 二、如果說Scanner使用簡(jiǎn)便,不如說Scanner的構(gòu)造器支持多種方式,構(gòu)建Scanner的對(duì)象很方便。 可以從字符串(Readable)、輸入流、文件等等來直接構(gòu)建Scanner對(duì)象,有了Scanner了,就可以逐段(根據(jù)正則分隔式)來掃描整個(gè)文本,并對(duì)掃描后的結(jié)果做想要的處理。 三、Scanner默認(rèn)使用空格作為分割符來分隔文本,但允許你指定新的分隔符 使用默認(rèn)的空格分隔符:         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 將注釋行去掉,使用空格或逗號(hào)或點(diǎn)號(hào)作為分隔符,輸出結(jié)果如下: 123  asdf sd 45 789 sdf asdfl sdf sdfl asdf asdfkl las Process finished with exit code 0 四、一大堆API函數(shù),實(shí)用的沒幾個(gè) (很多API,注釋很讓人迷惑,幾乎毫無用處,這個(gè)類就這樣被糟蹋了,啟了很不錯(cuò)的名字,實(shí)際上做的全是齷齪事) 下面這幾個(gè)相對(duì)實(shí)用: delimiter()  返回此 Scanner 當(dāng)前正在用于匹配分隔符的 Pattern。 hasNext() 判斷掃描器中當(dāng)前掃描位置后是否還存在下一段。(原APIDoc的注釋很扯淡) hasNextLine() 如果在此掃描器的輸入中存在另一行,則返回 true。 next() 查找并返回來自此掃描器的下一個(gè)完整標(biāo)記。 nextLine() 此掃描器執(zhí)行當(dāng)前行,并返回跳過的輸入信息。 五、逐行掃描文件,并逐行輸出 看不到價(jià)值的掃描過程         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()); } } package own;  import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.ProtocolException; import java.net.URL; import com.verisign.uuid.UUID; /** * ????????????????????????????????????????????? * @author wangpeng * */ public class AutoSubmit { /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { ...在此省略N行 Process finished with exit code 0 | 
|  |