Apache Common CLI:如何添加参数? [英] Apache Common CLI: How to add arguments?

查看:89
本文介绍了Apache Common CLI:如何添加参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将Common CLI用于个人项目.我没有从文档中找到的一件事是如何执行某个参数来表示.

I am using the Common CLI for a personal project. One thing I didn't find from the documentation is that how to enforce a certain argument to present.

为澄清我的问题,我可以定义参数和选项(命令)之间的区别吗?

To clarify my question, can I define the different between argument and option, the command:

    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

使用通用CLI,我可以将-b 2添加为这样的选项:

With Common CLI, I can add -b 2 as an option like this:

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

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

And parse the arguments using:

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

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

but how can I specify file.txt is also required?

非常感谢

推荐答案

我没意识到你是要制定目标(不是选项).

I didn't realize you meant make the target (not an option) to be required.

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

If you use the full parse methodCommandLineParser.parse(Options, String[], boolean) with the optional flag set to false, then the parser will skip over unknown arguments.

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

You can later retrieve them by the method getArgs() which returns a String[]

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

You can then go through those Strings to make sure there is a string called 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]打印到屏幕上.

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

so you add an extra check to search through that array to find any required targets:

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提供了一种干净的方法.

I agree it's messy but I don't think CLI provides a clean way to do this.

这篇关于Apache Common CLI:如何添加参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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