一、System.in
使用System.in获取控制台上输入的信息,每次只能读取一个字节的数据。利用数组缓冲也可以读取字符串。
- package Practice;
-
- public class ReaderConsole {
- public static void main(String[] args) {
- try{
- System.out.println("请输入字符串:");
-
- byte[] b = new byte[5];
-
- int n = System.in.read(b);
-
- String s = new String(b,0,n);
- System.out.println("输入的字符串为:" + s);
- }catch(Exception e){}
- }
- }
当我输入数据123456时,控制台显示:输入的字符串为12345,有最后一位6没有读取到。这是因为我在设置了用来缓冲数据的数组大小为5,即byte[] b = new byte[5];
所以这种方法是有弊端的,使用时要特别注意。
二、Scanner
使用Scanner可以获取控制台上的字符串。Scanner类中一些常用的方法:
(1)next()方法获取一个以space,tab或enter结束的字符串。
(2)nextInt()方法,将获取的字符串转换成整型。
(3)nextFloat()方法,将获取的字符串转换成浮点型。
(4)nextBloolean方法,将获取的字符串转换成布尔类型。
(5)nextLine()方法,获取输入的一行字符串(此方法与BufferedReader中的没有太大区别)
用法:
- Scanner sc=new Scanner(System.in);
- String s=sc.next();
三、BufferedReader
用法:
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in ));
- String read = null;
- System.out.print("请输入数据:");
- try {
- read = br.readLine();
- } catch (IOException e) {
- e.printStackTrace();
- }
- System.out.println("输入的数据为:"+read);
-
- }catch(Exception e){}