首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 標準輸入輸出實戰:鍵盤互動指令解析器完整實作

     編輯:Java 相關知識

構建一個互動式命令列工具,示範 Java 標準輸入(System.in)與標準輸出(System.out)的核心用法,包含緩衝讀取、指令解析、記憶體存儲與狀態機控制,適合作為 CLI 工具開發的起始範本。

核心功能

  • in:內容:新增內容到記憶體向量
  • out:列出所有已存內容
  • quit:退出程式

完整原始碼


import java.util.*;
import java.io.*;
public class StanderdIO {
    public static void main(String[] args) {
        Vector storage = new Vector<>();
        boolean running = true;
        // 建立緩衝讀取器包裝 System.in
        BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
        while (running) {
            System.out.print("input> ");
            String line;
            try {
                line = stdin.readLine(); // 阻塞等待用戶輸入
            } catch (IOException e) {
                System.err.println("IO error: " + e.getMessage());
                continue;
            }
            if (line == null) break; // EOF (Ctrl+D/Ctrl+Z)
            // 解析指令:格式 "cmd:context" 或單純 "cmd"
            String cmd = "", context = "";
            int colon = line.indexOf(':');
            if (colon == -1) cmd = line.trim();
            else { cmd = line.substring(0, colon).trim(); context = line.substring(colon + 1); }
            // 指令分發
            switch (cmd.toLowerCase()) {
                case "in":
                    if (context.isEmpty()) System.err.println("Error: 'in' requires content");
                    else storage.add(context);
                    break;
                case "out":
                    for (int i = 0; i < storage.size(); i++) 
                        System.out.println(i + ": " + storage.get(i));
                    break;
                case "quit":
                    running = false;
                    break;
                default:
                    System.err.println("Unknown command: " + cmd);
                    System.out.println("Usage: in:content | out | quit");
            }
        }
        System.out.println("Bye!");
    }
}

關鍵技術點解析

技術點說明
System.in標準輸入流(通常連接鍵盤),類型為 InputStream
InputStreamReader位元組流→字元流轉換器,指定編碼(預設平台編碼)
BufferedReader緩衝字元讀取器,提供高效 readLine() 按行讀取
readLine()阻塞直到換行符或 EOF,返回不含換行符的字串,EOF 返回 null
Vector執行緒安全的動態陣列,適合簡單單執行緒場景;現代代碼建議用 ArrayList

進階擴展方向

  1. 指令歷史:整合 java.io.Console 或 JLine 庫支援上下鍵翻歷史。
  2. 自動完成:Tab 鍵觸發指令/參數補全。
  3. 管道支援:檢測 System.in 是否為終端,非終端模式下批量處理管道輸入。
  4. 結構化輸出:JSON/表格格式化輸出,支援重導向到檔案。
  5. 非阻塞輸入:配合 Selector 或獨立執行緒實現即時互動。

現代化改寫建議 (JDK 9+)


// 使用 var 簡化聲明
var stdin = new BufferedReader(new InputStreamReader(System.in));
var storage = new ArrayList(); // 非執行緒安全場景優先 ArrayList
// 使用 switch expression (JDK 12+)
switch (cmd.toLowerCase()) {
    case "in" -> { if (context.isEmpty()) err("'in' requires content"); else storage.add(context); }
    case "out" -> storage.forEach((i, s) -> System.out.println(i + ": " + s));
    case "quit" -> running = false;
    default -> { err("Unknown: " + cmd); System.out.println("Usage: in:content | out | quit"); }
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved