Java Commons CLI中不带选项名的必需参数
我试图将Java中的命令行参数解析为以下用法:Java Commons CLI中不带选项名的必需参数,java,apache-commons-cli,Java,Apache Commons Cli,我试图将Java中的命令行参数解析为以下用法: Usage: gibl FILE -h, --help Displays this help message. -v, --version Displays the program version. FILE Source file. 有了Apache Commons CLI库,我知道我可以使用选项选择性地解析-h和-v命令,然后使用命令行.getArgs()获取剩余参数文件,然后按我喜欢的方式解析
Usage: gibl FILE
-h, --help Displays this help message.
-v, --version Displays the program version.
FILE Source file.
有了Apache Commons CLI库,我知道我可以使用选项
选择性地解析-h
和-v
命令,然后使用命令行.getArgs()
获取剩余参数文件
,然后按我喜欢的方式解析它,但实际上我想在CLI中将其指定为选项
目前,我做了以下工作:
if (cmd.getArgs().length < 1) {
System.out.println("Missing argument: FILE");
help(1); // Prints the help file and closes the program with an exit code of 1.
}
String file = cmd.getArgs()[0];
其中我有一个参数,但没有相应的选项标识符附加到它,因此可以将其传递给
帮助格式化程序
。有什么想法吗?据我所知,Commons CLI不支持定义没有相关标志的选项。我认为你需要做以下几点:
new HelpFormatter().printHelp("commandName [OPTIONS] <FILE>", Options);
newhelpformatter().printHelp(“commandName[OPTIONS]”,OPTIONS);
如果您没有看到,它非常相似,我的答案与这里的答案非常相似。Apache Commons CLI 1.4:
您可以通过以下方式访问无关联标志的命令行参数:
org.apache.commons.cli.CommandLine#getArgList()
它返回所有未使用/解析的参数的列表
因此,您可以通过以下方式获得定义的选项:
org.apache.commons.cli.CommandLine#getOptionValue(“选项名”)
org.apache.commons.cli.CommandLine#haspoption(“选项名称”)
- (……)
org.apache.commons.cli.CommandLine#getArgList()
。谢谢你,柯比。很快,您发布的字符串是定义选项和文件的POSIX标准方式吗?只是想让它看起来尽可能真实。我绝不是POSIX专家。但我知道,在Unix世界中,Unix使用消息中习惯于将可选项括在方括号内,并用裸字或尖括号表示必填项。我认为我发布的字符串将经得起Unix忠实用户的仔细检查。好的,非常感谢Kirby!我还随意添加了一个System.out.println(“文件”)代码>打印消息后的行,使其与选项同时显示。谢谢你的回答!
new HelpFormatter().printHelp("commandName [OPTIONS] <FILE>", Options);