一、使用System.in.read()一次獲取一個字節
輸入再多數據,只會獲取第一個字節的int形式。獲取的是字節,而不是字符,所以如果輸入中文字符,強轉后會得到亂碼
1 try { 2 int in_num=System.in.read(); //獲取的是一個字節的int類型 3 System.out.println("強轉前:"+in_num); 4 System.out.println("強轉后:"+(char)in_num); 5 } catch (IOException e) { 6 e.printStackTrace(); 7 }
1.輸入:你
強轉前:196 強轉后:?
2.輸入:@
強轉前:64 強轉后:@
3.輸入:space(一個空格)
強轉前:32 強轉后: //強轉后得到的是一個空格,有占位。只是看不到而已
4.輸入:enter(換行)
強轉前:13 強轉后: //強轉后得到的是一個換行。
5.輸入:tab(水平制表符)
強轉前:9 強轉后: //強轉后得到的是一個水平制表符(8個空格)
二、使用Scanner獲取
1 Scanner in=new Scanner(System.in); 2 System.out.println("獲取字符串:"+in.next()); 3 //System.out.println("獲取一行數據:"+in.nextLine());
1.單獨用in.next()方法獲取字符串,輸入tab、space、enter時,會從這里為斷點,只會獲取之前的數據,如:
輸入:我愛 你到底 獲取字符串:我愛 //會自動去除前后的空格trim()方法
2.單獨用in.nextLine()方法獲取一行輸入的數據,無論輸入tab、space都會完整的獲取到,當輸入enter時,表示輸入完畢。
輸入數據:讓 我深深 去愛你
獲取一行數據:讓 我深深 去愛你 //不會去除前后的空格
3.如果使用完in.next()后沒有關閉,就使用in.nextLine(),則in.nextLine()會獲取前一方法截斷后的數據。
如果關閉后還執行in.nextLine()則會拋出異常:java.lang.IllegalStateException: Scanner closed
輸入:我留不住 所有的歲月
獲取字符串:我留不住
獲取一行數據: 所有的歲月
三、使用BufferedReader獲取數據
1 InputStream is=System.in; 2 InputStreamReader isr=new InputStreamReader(is); 3 BufferedReader br=new BufferedReader(isr); 4 try { 5 System.out.println(br.readLine()); 6 } catch (IOException e) { 7 e.printStackTrace(); 8 }
1.獲取一個字符的int類型:br.read();
2.獲取一行字符串:br.readLine(); //不會自動去除前后空格
3.把獲取到的數據裝入到一個char[]數組中。返回的是這個數據的長度
int length=br.read(char[]);
(個人學習筆記,有錯請說出來。謝謝!)