- package bin;
- import java.util.Scanner;
- public class ScannerKeyBoardTest
- {
- public static void main(String[] args)
- {
- //System.in代表标准输入,就是键盘输入
- Scanner sc = new Scanner(System.in);
- sc.useDelimiter("\n");//只把回车作为分隔符
- while(sc.hasNext())
- {
- System.out.println("键盘输入的是:"+ sc.next());
- }
- }
- }
使用Scanner读取文件内容:
- package bin;
- import java.util.Scanner;
- import java.io.File;
- public class ScannerFileTest
- {
- public static void main(String[] args)throws Exception
- {
- //将一个File对象作为Scanner的构造器参数,Scanner读取文件内容
- Scanner sc = new Scanner(new File("F://javasrc/1006/bin/ScannerFileTest.java"));
- System.out.println("ScannerFileTest.java文件内容如下:");
- while(sc.hasNext())//判断是否还有下一行
- {
- System.out.println(sc.nextLine());
- }
- }
- }
使用BufferedReader获取键盘输入:
- package bin;
- import java.util.Scanner;
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- public class KeyboardInTest
- {
- public static void main(String[] args)throws Exception
- {
- //以System.in字节流为基础,创建一个BufferedReader对象
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- String line = null;
- //逐行读取键盘输入
- while((line = br.readLine())!= null)
- {
- System.out.println("用户输入的是:"+ line);
- }
- }
- }
用户的每次输入都被BufferedReader当成String对象,与Scanner不同的是,BufferrdReader不能读取基本类型输入项,他总是读取String对象。