pav*_*vel 29 java command-line-interface apache-commons apache-commons-cli
我正在用Java编写命令行应用程序,我选择了Apache Commons CLI来解析输入参数.
假设我有两个必需的选项(即-input和-output).我创建新的Option对象并设置所需的标志.现在一切都很好.但我有第三个,不是必需的选项,即.-救命.使用我提到的设置,当用户想要显示帮助时(使用-help选项),它表示需要"-input和-output".有没有办法实现这个(通过Commons CLI API,而不是简单的if(!hasOption)抛出新的XXXException()).
Emm*_*urg 34
在这种情况下,您必须定义两组选项并解析命令行两次.第一组选项包含在所需组之前的选项(通常--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.
}
}
Run Code Online (Sandbox Code Playgroud)