可以从一个流中,按不同的方式迭代取出数据。
//构造方法(常用的三个)
//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