English 中文(简体)
GNU Parser
  • 时间:2024-09-17

Apache Commons CLI - GNU Parser


Previous Page Next Page  

A GNU parser is use to parse gnu pke arguments passed. It is now deprecated and is replaced by DefaultParser.

Example

CLITester.java


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

pubpc class CLITester {
   pubpc static void main(String[] args) throws ParseException {
      
      //Create GNU pke 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"));
      }
   }
}

Output

Run the file while passing -p -g -n 10 as option and see the result.


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