
- Commons CLI - Home
- Commons CLI - Overview
- Commons CLI - Environment Setup
- Commons CLI - First Application
- Commons CLI - Option Properties
- Commons CLI - Boolean Option
- Commons CLI - Argument Option
- Commons CLI - Properties Option
- Commons CLI - Posix Parser
- Commons CLI - GNU Parser
- Commons CLI - Usage Example
- Commons CLI - Help Example
- Apache Commons CLI Resources
- Commons CLI - Quick Guide
- Commons CLI - Useful Resources
- Commons CLI - Discussion
Apache Commons CLI - GNU Parser
A GNU parser is use to parse gnu like arguments passed. It is now deprecated and is replaced by DefaultParser.
Example
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")); } } }
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