📜  Apache Commons CLI-GNU解析器

📅  最后修改于: 2020-11-18 08:02:04             🧑  作者: Mango


GNU解析器用于解析类似传递的参数的gnu。现在已弃用,并由DefaultParser代替。

CLITester.java

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

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

      //Create GNU like options
      Options gnuOptions = new Options();
      gnuOptions.addOption("p", "print", false, "Print")
         .addOption("g", "gui", false, "GUI")
         .addOption("n", true, "Scale");

      CommandLineParser gnuParser = new GnuParser();
      CommandLine cmd = gnuParser.parse(gnuOptions, args);

      if( cmd.hasOption("p") ) {
         System.out.println("p option was used.");
      }
      
      if( cmd.hasOption("g") ) {
         System.out.println("g option was used.");
      }
      
      if( cmd.hasOption("n") ) {
         System.out.println("Value passed: " + cmd.getOptionValue("n"));
      }
   } 
}

输出

在传递-p -g -n 10作为选项的同时运行文件,并查看结果。

java CLITester -p -g -n 10
p option was used.
g option was used.
Value passed: 10