Commons CLI需要组
我正在用Java编写命令行应用程序,我选择了Apache Commons CLI来解析输入参数。
假设我有两个必需的选项 (即-input和-output)。 我创建新的Option对象并设置必需的标志。 现在一切都很好。 但我有第三个,不是必需的选项 ,即。 -救命。 使用我提到的设置,当用户想要显示帮助时(使用-help选项),它表示需要“-input和-output”。 有没有办法实现这个(通过Commons CLI API,不简单,如果(!hasOption)抛出新的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. } }
- 用于压缩(例如LZW)字符串的Java库
- 如何使用commons dbutils生成密钥?
- FTPClient.listFiles无法正常工作
- 文件上传“multipart / form”exceptionorg.apache.commons.fileupload.FileUploadBase $ InvalidContentTypeException
- 来自apache-commons exec的进程输出
- apache commons压缩的tar问题
- 如何将字符串参数传递给使用Apache Commons Exec启动的可执行文件?
- 通过Java lib Apache Commons上传文件的简明示例
- apache commons配置加载属性,直到“,”字符