Commons CLI需要组

时间:2012-05-29 11:26:29

标签: java command-line-interface apache-commons apache-commons-cli

我正在用Java编写命令行应用程序,我选择了Apache Commons CLI来解析输入参数。

假设我有两个必需选项(即-input和-output)。我创建新的Option对象并设置所需的标志。现在一切都很好。但我有第三,不是必需的选项,即。 -救命。使用我提到的设置,当用户想要显示帮助时(使用-help选项),它表示需要“-input和-output”。有没有办法实现这个(通过Commons CLI API,不简单,如果(!hasOption)抛出新的XXXException())。

2 个答案:

答案 0 :(得分:30)

在这种情况下,您必须定义两组选项并解析命令行两次。第一组选项包含所需组之前的选项(通常为--help--version),第二组包含所有选项。

首先解析第一组选项,如果找不到匹配项,则继续第二组选项。

以下是一个例子:

Options options1 = new Options();
options1.add(OptionsBuilder.withLongOpt("help").create("h"));
options1.add(OptionsBuilder.withLongOpt("version").create());

// this parses the command line but doesn't throw an exception on unknown options
CommandLine cl = new DefaultParser().parse(options1, args, true);

if (!cl.getOptions().isEmpty()) {

    // print the help or the version there.

} else {
    OptionGroup group = new OptionGroup();
    group.add(OptionsBuilder.withLongOpt("input").hasArg().create("i"));
    group.add(OptionsBuilder.withLongOpt("output").hasArg().create("o"));
    group.setRequired(true);

    Options options2 = new Options();
    options2.addOptionGroup(group);

    // add more options there.

    try {
        cl = new DefaultParser().parse(options2, args);

        // do something useful here.

    } catch (ParseException e) {
        // print a meaningful error message here.
    }
}

答案 1 :(得分:0)

commons-cli库有一个流畅的包装器:https://github.com/bogdanovmn/java-cmdline-app

帮助选项是内置的。也有一些方便的功能。 例如,如果您必须指定两个选项之一:

new CmdLineAppBuilder(args)
// Optional argument
.withArg("input", "input description")
.withArg("output", "output description")

// "input" or "output" must be specified
.withAtLeastOneRequiredOption("input", "output")

.withEntryPoint(
    cmdLine -> {
        ...
    }
).build().run();