Apache Common CLI:如何添加参数? [英] Apache Common CLI: How to add arguments?
问题描述
我将通用 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
使用 Common 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.
您可以稍后通过返回 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屋!