Commons Cli 简明教程

Apache Commons CLI - Posix Parser

Posix 解析器用于解析类似于 Posix 的传递的参数。它现在已被弃用,并已被 DefaultParser 替换。

Example

CLITester.java

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;

public class CLITester {
   public static void main(String[] args) throws ParseException {

      //Create posix like options
      Options posixOptions = new Options();
      posixOptions.addOption("D", false, "Display");
      posixOptions.addOption("A", false, "Act");

      CommandLineParser posixParser = new PosixParser();

      CommandLine cmd = posixParser.parse(posixOptions, args);

      if( cmd.hasOption("D") ) {
         System.out.println("D option was used.");
      }
      if( cmd.hasOption("A") ) {
         System.out.println("A option was used.");
      }
   }
}

Output

运行文件,同时传递 -D -A 作为选项并查看结果。

java CLITester -D -A
D option was used.
A option was used.

运行文件,同时传递 --D 作为选项并查看结果。

java CLITester --D
D option was used.