Commons Cli 简明教程
Apache Commons CLI - Properties Option
Properties 选项在命令行上由其名称及其相应属性(如语法)表示,类似于 Java 属性文件。考虑以下示例,如果我们要传递以下选项 -DrollNo = 1 -Dclass = VI -Dname = Mahesh,我们应该将每个值作为属性进行处理。让我们看一看实现逻辑。
Example
CLITester.java
import java.util.Properties;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public class CLITester {
public static void main(String[] args) throws ParseException {
Options options = new Options();
Option propertyOption = Option.builder()
.longOpt("D")
.argName("property=value" )
.hasArgs()
.valueSeparator()
.numberOfArgs(2)
.desc("use value for given properties" )
.build();
options.addOption(propertyOption);
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse( options, args);
if(cmd.hasOption("D")) {
Properties properties = cmd.getOptionProperties("D");
System.out.println("Class: " + properties.getProperty("class"));
System.out.println("Roll No: " + properties.getProperty("rollNo"));
System.out.println("Name: " + properties.getProperty("name"));
}
}
}