可以從一個流中,按不同的方式迭代取出數據。
//構造方法(常用的三個)
//Scanner(File source)
//Scanner(InputStream source)
//Scanner(String source)
useDelimiter(“”) 確定分割的符號,默認空格
常用方法:
hasNext()
hasInt()
hasNextLine()
next()
nextLine()
例子,讀取文件的每一行並輸出
public class ScannerDemo {
public static void main(String[] args){
demo();
}
public static void demo(){
try {
FileReader freader = new FileReader("src/data.txt");// 因爲IDE會把項目的路徑寫入classpath,所以可以以項目的根路徑作爲相對路徑,否則要寫絕對路徑
Scanner scanner = new Scanner(freader);
while(scanner.hasNextLine()){
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
輸出
a b c d e 1 2 3
e f g h
i j k l