1、Scanner是SDK1.5新增的一個類,可是使用該類創建一個對象.
Scanner reader=new Scanner(System.in);
2、reader對象調用下列方法(函數),讀取用戶在命令行輸入的各種數據類型:next.Byte(),nextDouble(),nextFloat,nextInt(),nextLine(),nextLong(),nextShot()上述方法執行時都會造成堵塞,等待用戶在命令行輸入數據回車確認.
可以從字符串(Readable)、輸入流、文件等等來直接構建Scanner對象,有了Scanner了,就可以逐段(根據正則分隔式)來掃描整個文本,並對掃描后的結果做想要的處理。
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class ScannerDemo { public static void main(String[] args) throws Exception { //掃描文件中的數據 //Scanner s=new Scanner(new File("file/text.txt"),"GBK"); //掃描鍵盤中的數據 Scanner s=new Scanner(System.in); while(s.hasNextLine()){ String content=s.nextLine(); System.out.println("ECHO:"+content); } s.close(); } }
三、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());
}
}
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