我們很熟悉用 System.out.print 往終端機輸出,但要「讀進來」就得靠它的對偶:System.in.read()。它會把輸入的位元組寫入指定的 byte 陣列,使用者按下 Enter(Return)後才返回。
package com.han;
import java.io.*;
/**
* 從預設命令列介面讀取使用者輸入的資料。
* 使用 System.in.read,與 System.out.print 相對。
* @author han
*/
public class InputSystem{
public static void main(String args[]){
byte[] buffer = new byte[512];
try {
System.out.print("請你輸入: ");
System.in.read(buffer); // 輸入資料後以 Enter 結束
} catch (IOException e) {
e.printStackTrace();
}
String str = new String(buffer);
System.out.println("what you input is: " + str);
}
}
第一,read 回傳的是實際讀入的位元組數,但範例沒有接住它,於是 new String(buffer) 會把 512 個位元全部轉字串,尾端出現一串看起來像亂碼的字元。改寫成 int n = System.in.read(buffer); 再用 new String(buffer, 0, n) 就乾淨了。
第二,若輸入的是中文,建議明確指定編碼,例如 new String(buffer, 0, n, "UTF-8"),避免不同平台預設編碼不同而產生亂碼。若只是要讀一行文字,用 BufferedReader 包 InputStreamReader 會比裸的 System.in.read 更省事。