gpt4 book ai didi

java - Commons CLI 所需的组

转载 作者:IT老高 更新时间:2023-10-28 21:08:50 25 4
gpt4 key购买 nike

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

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

最佳答案

在这种情况下,您必须定义两组选项并解析命令行两次。第一组选项包含所需组之前的选项(通常是 --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.
}
}

关于java - Commons CLI 所需的组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10798208/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com