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

Jakarta Commons CLI 使用指南:命令行參數解析與幫助生成

     編輯:Java 相關知識

核心能力

  • 定義選項規則 (短/長名、是否需參數、描述)
  • 自動解析 String[] args,類型轉換
  • 生成標準用法幫助信息
  • 支援 POSIX、GNU、Java 等多種風格

Maven 依賴

<dependency>
  <groupId>commons-cli</groupId>
  <artifactId>commons-cli</artifactId>
  <version>1.4</version>
</dependency>

完整範例:互動式命令解析

public class OptionsTip {
    public static void main(String[] args) throws Exception {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String line = in.readLine(); // 從控制檯讀取命令行
        args = line.split(" ");

        Options options = new Options();
        options.addOption("h", false, "Print help for this application");
        options.addOption("u", true, "The username to use");
        options.addOption("dsn", true, "The data source to use");

        CommandLineParser parser = new BasicParser();
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption('h')) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("OptionsTip", options);
        } else {
            System.out.println("Username: " + cmd.getOptionValue("u"));
            System.out.println("DataSource: " + cmd.getOptionValue("dsn"));
        }
    }
}

執行效果

輸入: -h
輸出:
usage: OptionsTip
 -dsn <arg> The data source to use
 -h     Print help for this application
 -u <arg> The username to use

輸入: -u admin -dsn mysql
輸出:
Username: admin
DataSource: mysql

進階特性

  • OptionGroup:互斥選項組
  • PatternOptionBuilder:簡化選項定義語法
  • GnuParser / PosixParser:支援長選項 (--username)、短選項合併 (-uv)
  • 類型轉換:cmd.getOptionValue("port", Integer.class)

最佳實踐

  1. 在 main 入口統一解析,構建配置對象
  2. 區分必選/可選選項,缺失時拋出友好錯誤
  3. 整合 HelpFormatter 提供自助文檔
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved