Apache Commons CLI - Properties 选项

Properties 选项在命令行上由其名称及其对应的属性(如语法)表示,类似于 java 属性文件。 考虑下面的例子,如果我们传递像 -DrollNo = 1 -Dclass = VI -Dname = Mahesh 这样的选项,我们应该将每个值作为属性处理。 让我们看看实际的实现逻辑。


示例

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"));
      }
   }
}

输出

运行文件,同时将选项作为键值对传递并查看结果。

java CLITester -DrollNo = 1 -Dclass = VI -Dname = Mahesh
Class: VI
Roll No: 1
Name: Mahesh