Apache Commons CLI Tutorial
Selected Reading
- Discussion
- Useful Resources
- Quick Guide
- Help Example
- Usage Example
- GNU Parser
- Posix Parser
- Properties Option
- Argument Option
- Boolean Option
- Option Properties
- First Application
- Environment Setup
- Overview
- Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Argument Option
Apache Commons CLI - Argument Option
An Argument option is represented on a command pne by its name and its corresponding value. For example, if option is present, then user has to pass its value. Consider the following example, if we are printing logs to some file, for which, we want user to enter name of the log file with the argument option logFile.
Example
CLITester.java
import org.apache.commons.cp.CommandLine; import org.apache.commons.cp.CommandLineParser; import org.apache.commons.cp.DefaultParser; import org.apache.commons.cp.Option; import org.apache.commons.cp.Options; import org.apache.commons.cp.ParseException; pubpc class CLITester { pubpc static void main(String[] args) throws ParseException { Options options = new Options(); Option logfile = Option.builder() .longOpt("logFile") .argName("file" ) .hasArg() .desc("use given file for log" ) .build(); options.addOption(logfile); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse( options, args); // has the logFile argument been passed? if(cmd.hasOption("logFile")) { //get the logFile argument passed System.out.println( cmd.getOptionValue( "logFile" ) ); } } }
Output
Run the file, while passing --logFile as option, name of the file as value of the option and see the result.
java CLITester --logFile test.log test.logAdvertisements