java.util.Scanner 是 Java 5 引入的文本掃描器,支援正則分割、類型安全讀取、多源輸入 (標準輸入/文件/字符串/流)。本文從基礎到進階全面講解。
Scanner sc = new Scanner(System.in); // 或 new Scanner(new File("data.txt"))
String str = sc.next(); // 讀取下一個 token (默認空白分隔)
int i = sc.nextInt(); // 讀取 int
long l = sc.nextLong(); // 讀取 long
double d = sc.nextDouble(); // 讀取 double
boolean b = sc.nextBoolean(); // 讀取 boolean
BigInteger bi = sc.nextBigInteger();
BigDecimal bd = sc.nextBigDecimal();
關鍵: 先調用 hasNextXxx() 判斷是否有下一個對應類型 token,避免 InputMismatchException/NoSuchElementException。
Scanner s = new Scanner(System.in);
System.out.println("輸入 'exit' 退出:");
while (true) {
String line = s.nextLine(); // 讀取整行 (含空格)
if ("exit".equals(line)) break;
System.out.println(">>> " + line);
}
nextLine() 讀取至換行符,**不消耗分隔符**,適合行處理。混用 next() 和 nextLine() 時注意換行符殘留問題。
try (Scanner sc = new Scanner(new File("numbers.txt"))) {
while (sc.hasNextDouble()) {
System.out.println(sc.nextDouble());
}
} catch (FileNotFoundException e) { e.printStackTrace(); }
try-with-resources 自動關閉資源 (Java 7+)。
// 默認空白分隔
Scanner s1 = new Scanner("123 abc 456");
while (s1.hasNext()) System.out.println(s1.next());
// 123 / abc / 456
// 自定義:空格 或 逗號 或 點號
Scanner s2 = new Scanner("123, abc.456").useDelimiter("\\s*[,|.]\\s*");
while (s2.hasNext()) System.out.println(s2.next());
// 123 / abc / 456
useDelimiter(Pattern) 可傳入編譯後 Pattern 對象,復用更高效。
String input = "1 fish 2 fish red fish blue fish";
// 方式一:分隔符模式 (簡單)
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt()); // 1
System.out.println(s.nextInt()); // 2
System.out.println(s.next()); // red
System.out.println(s.next()); // blue
s.close();
// 方式二:findInLine + MatchResult (強大,提取捕獲組)
String input2 = "1 fish 2 fish red fish blue fish";
Scanner s2 = new Scanner(input2);
s2.findInLine("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)");
MatchResult r = s2.match();
for (int i = 1; i <= r.groupCount(); i++) {
System.out.println("Group " + i + ": " + r.group(i));
}
// Group 1: 1
// Group 2: 2
// Group 3: red
// Group 4: blue
s2.close();
優勢: 直接獲取命名/編號捕獲組,無需手動 Pattern/Matcher 繁瑣代碼。
try (Scanner sc = new Scanner(new File("myNumbers"))) {
while (sc.hasNextLong()) {
long aLong = sc.nextLong();
// 處理...
}
}
Scanner 默認用系統 Locale 解析數字 (如德語 1.234,56),解析標準格式請 sc.useLocale(Locale.US)。new Scanner(file, "UTF-8", 1024*1024) 設置 1MB 緩衝。hasNext() 會阻塞等待輸入,控制台交互無問題,網絡流需謹慎。close() 會關閉底層 Readable (如 System.in 關閉後無法重開),文件掃描器用完即關,標準輸入**慎用 close()**。| 特性 | Scanner | BufferedReader | Files.lines() (Stream) |
|---|---|---|---|
| 解析基本類型 | ✅ 內建 | ❌ 手動 parse | ❌ map 轉換 |
| 正則分割 | ✅ 靈活 | ❌ 手動 split | ✅ splitAsStream |
| 行讀取 | nextLine() | readLine() | 流元素即行 |
| 性能 (大文件) | 中 (正則開銷) | 高 (單純讀行) | 高 (並行流) |
| 適用場景 | 交互輸入、結構化文本解析 | 大文本逐行處理 | 大數據流式處理/並行 |
選對工具,代碼簡潔且高效。