java - Apache 通用 CLI : How to add arguments?

标签 java apache-commons

我正在为个人项目使用 Common CLI。我没有从文档中找到的一件事是如何强制提出某个论点。

为了澄清我的问题,我可以定义参数和选项之间的区别,命令:

    mycommand file.txt -b 2

mycommand is the command, 
file.txt is the argument
-b 2 is the option where 2 is the option value

使用 Common CLI,我可以像这样添加 -b 2 作为选项:

    options.addOption( "b", true, "Some message" );

并使用以下方法解析参数:

CommandLineParser commandParser = new GnuParser();
CommandLine result = commandParser.parse(options, args)

但是如何指定 file.txt 也是必需的?

非常感谢

最佳答案

编辑:我没有意识到你的意思是使目标(而不是一个选项)成为必需的。

如果您使用完整的解析方法CommandLineParser.parse(Options, String[], boolean) 并将可选标志设置为 false,则解析器将跳过未知参数。

您稍后可以通过返回 String[] 的方法 getArgs() 检索它们

然后您可以遍历这些字符串以确保有一个名为 file.txt 的字符串

Options options = new Options();

options.addOption("b", true, "some message");

String[] myArgs = new String[]{"-b","2", "file.txt"};
CommandLineParser commandParser = new GnuParser();

CommandLine commandline = commandParser.parse(options, myArgs, false);

System.out.println(Arrays.toString(commandline.getArgs()));

将打印 [file.txt] 到屏幕。

因此您添加一个额外的检查来搜索该数组以找到任何所需的目标:

boolean found=false;
for(String unparsedTargets : commandline.getArgs()){
    if("file.txt".equals(unparsedTargets)){
        found =true;
    }
}
if(!found){
    throw new IllegalArgumentException("must provide a file.txt");
}

我同意这很困惑,但我不认为 CLI 提供了一种干净的方式来做到这一点。

关于java - Apache 通用 CLI : How to add arguments?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18344088/

相关文章:

java - 记录完整堆栈跟踪性能问题

java - 如何用JAVA向文件中写入特定数据

java - 如何在 Java 中检查以下实例?

java - 字节数组实际长度

java - Android 内存不足错误?

redis - jedis 连接设置以实现高性能和可靠性

java - Spring AOP 介绍中丢失了原有的接口(interface)

java - 如何将Excel单元格值插入到列表中?

java - prunsrv.exe 服务未启动

java - Apache Commons HttpComponents 示例