Commons Cli 简明教程
Apache Commons CLI - Overview
Apache Commons CLI 是 Apache Commons 的组件,它源自 Java API,并提供一个 API 来解析传递给程序的命令行参数/选项。此 API 还支持输出与可用选项有关的帮助信息。
The Apache Commons CLI are the components of the Apache Commons which are derived from Java API and provides an API to parse command line arguments/options which are passed to the programs. This API also enables to print help related to options available.
命令行处理包含三个阶段。这些阶段在下面进行了说明 -
Command line processing comprises of three stages. These stages are explained below −
-
Definition Stage
-
Parsing Stage
-
Interrogation Stage
Definition Stage
在定义阶段,我们定义应用程序可以使用的选项,并根据实际情况操作。Commons CLI 提供 Options 类,该类是 Option 对象的容器。
In definition stage, we define the options that an application can take and act accordingly. Commons CLI provides Options class, which is a container for Option objects.
// create Options object
Options options = new Options();
// add a option
options.addOption("a", false, "add two numbers");
这里我们添加了一个选项标志 a,而第二个参数为 false,表明该选项不是必需的,而第三个参数表明该选项的描述。
Here we have added an option flag a, while false as second parameter, signifies that option is not mandatory and third parameter states the description of option.
Parsing Stage
在解析阶段,我们在创建解析器实例后解析使用命令行参数传递的选项。
In parsing stage, we parse the options passed using command line arguments after creating a parser instance.
//Create a parser
CommandLineParser parser = new DefaultParser();
//parse the options passed as command line arguments
CommandLine cmd = parser.parse( options, args);
Interrogation Stage
在查询阶段,我们检查是否存在特定选项,然后相应地处理该命令。
In Interrogation stage, we check if a particular option is present or not and then, process the command accordingly.
//hasOptions checks if option is present or not
if(cmd.hasOption("a")) {
// add the two numbers
} else if(cmd.hasOption("m")) {
// multiply the two numbers
}