Java 提供三種主流方式從標準輸入讀取資料,各有適用版本與特色。
最經典、相容性最好,需手動處理編碼與緩衝。
import java.io.*;
public class ConsoleInputDemo1 {
public static void main(String[] args) {
String input = readLine("請輸入字串:");
System.out.println("您輸入:" + input);
}
private static String readLine(String prompt) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print(prompt);
try {
return br.readLine();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
功能豐富,支援基本型別解析、正則分隔、檔案掃描。
import java.util.Scanner;
public class ConsoleInputDemo2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("請輸入整數:");
int num = scanner.nextInt(); // 直接解析 int
System.out.print("請輸入字串:");
String str = scanner.next(); // 以空白分隔
System.out.println("數字:" + num + ",字串:" + str);
// 進階:掃描檔案並求和
// Scanner fileScanner = new Scanner(new File("num.txt"));
// while (fileScanner.hasNextDouble()) sum += fileScanner.nextDouble();
}
}
專為互動式終端機設計,支援**密碼無回顯**,API 更簡潔。
import java.io.Console;
public class ConsoleInputDemo3 {
public static void main(String[] args) {
Console console = System.console();
if (console == null) {
System.err.println("無法取得 Console (可能在 IDE 執行),請在終端機運行。");
return;
}
String username = console.readLine("Username: ");
char[] password = console.readPassword("Password: "); // 無回顯!
if ("admin".equals(username) && "123456".equals(new String(password))) {
console.printf("歡迎 %s 登入系統%n", username);
} else {
console.printf("帳號或密碼錯誤%n");
}
// 安全性:用畢立即清空密碼陣列
java.util.Arrays.fill(password, ' ');
}
}
| 特性 | BufferedReader | Scanner | Console |
|---|---|---|---|
| 最低 JDK | 1.4 | 1.5 | 1.6 |
| 密碼無回顯 | 需自行實作 | 不支援 | 原生支援 readPassword() |
| 型別解析 | 手動轉換 | 內建 nextInt() 等 | 手動轉換 |
| 正則分隔 | 不支援 | 支援 useDelimiter() | 不支援 |
| 檔案掃描 | 需包裝 FileReader | 直接 new Scanner(file) | 不支援 |
| IDE 相容性 | 完美 | 完美 | 通常為 null (輸出重導向) |
| 編碼控制 | InputStreamReader 指定 | Scanner 建構子指定 | 預設系統編碼 |
Scanner 功能最完整、程式碼最簡潔。Console.readPassword(),並立即清空 char[]。BufferedReader。Console (回傳 null),改用 Scanner 或 BufferedReader。Scanner sc = new Scanner("2 2.2 3.3 done");
double sum = 0;
while (sc.hasNext()) {
if (sc.hasNextDouble()) {
sum += sc.nextDouble();
} else {
String token = sc.next();
if ("done".equals(token)) break;
else throw new RuntimeException("格式錯誤: " + token);
}
}
System.out.println("Sum = " + sum); // 7.5