【问题标题】:How to fetch parameters when using the Apache Commons CLI library使用 Apache Commons CLI 库时如何获取参数
【发布时间】:2011-06-09 00:54:03
【问题描述】:

我正在使用 Apache Commons CLI 来处理 Java 中的命令行参数。

我已经声明了ab 选项,并且可以使用CommandLine.getOptionValue() 访问该值。

Usage: myapp [OPTION] [DIRECTORY]

Options:
-a        Option A
-b        Option B

如何声明和访问 DIRECTORY 变量?

【问题讨论】:

  • 你是怎么把HelpFormatter打印成[OPTION] [DIRECTORY]的?

标签: java apache-commons apache-commons-cli


【解决方案1】:

最好使用另一个选项 (-d) 来识别对用户来说更直观的目录。

或者下面的代码演示了获取剩余的参数列表

public static void main(final String[] args) {
    final CommandLineParser parser = new BasicParser();
    final Options options = new Options();
    options.addOption("a", "opta", true, "Option A");
    options.addOption("b", "optb", true, "Option B");

    final CommandLine commandLine = parser.parse(options, args);

    final String optionA = getOption('a', commandLine);
    final String optionB = getOption('b', commandLine);

    final String[] remainingArguments = commandLine.getArgs();

    System.out.println(String.format("OptionA: %s, OptionB: %s", optionA, optionB));
    System.out.println("Remaining arguments: " + Arrays.toString(remainingArguments));
}

public static String getOption(final char option, final CommandLine commandLine) {

    if (commandLine.hasOption(option)) {
        return commandLine.getOptionValue(option);
    }

    return StringUtils.EMPTY;
}

【讨论】:

  • 对此,我要补充一点,HelpFormatter 将用于打印 [DIRECTORY] 参数:HelpFormatter formatter = new HelpFormatter();formatter.printHelp("myapp [OPTION] [DIRECTORY]", options);
【解决方案2】:

使用以下方法:

CommandLine.getArgList()

在处理完选项后返回剩余的内容。

【讨论】:

  • 如果所有选项的参数数量不限怎么办?
猜你喜欢
  • 2013-03-08
  • 1970-01-01
  • 1970-01-01
  • 2016-02-25
  • 2014-08-15
  • 2013-06-15
  • 2011-11-18
  • 1970-01-01
  • 2012-01-25
相关资源
最近更新 更多