Commons CLI需要组 [英] Commons CLI required groups

查看:124
本文介绍了Commons CLI需要组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am writing command line application in Java and I've chosen Apache Commons CLI to parse input arguments.

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

Let's say I have two required options (ie. -input and -output). I create new Option object and set required flag. For now it's all good. But I have third, not required option, ie. -help. With settings that I've mentioned, when user wants to show help (use -help option) it says "-input and -output" are required. Is there any way to implement this (via Commons CLI API, not simple if (!hasOption) throw new XXXException()).

推荐答案

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

In this situation you have to define two sets of options and parse the command line twice. The first set of options contains the options that precede the required group (typically --help and --version), and the second set contains all the options.

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

You start by parsing the first set of options, and if no match is found, you go on with the second set.

以下是一个例子:

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.
    }
}

这篇关于Commons CLI需要组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆