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
Properties Option
Apache Commons CLI - Properties Option
A Properties option is represented on a command pne by its name and its corresponding properties pke syntax, which is similar to java properties file. Consider the following example, if we are passing options pke -DrollNo = 1 -Dclass = VI -Dname = Mahesh, we should process each value as properties. Let s see the implementation logic in action.
Example
CLITester.java
import java.util.Properties; 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 propertyOption = Option.builder() .longOpt("D") .argName("property=value" ) .hasArgs() .valueSeparator() .numberOfArgs(2) .desc("use value for given properties" ) .build(); options.addOption(propertyOption); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse( options, args); if(cmd.hasOption("D")) { Properties properties = cmd.getOptionProperties("D"); System.out.println("Class: " + properties.getProperty("class")); System.out.println("Roll No: " + properties.getProperty("rollNo")); System.out.println("Name: " + properties.getProperty("name")); } } }
Output
Run the file, while passing options as key value pairs and see the result.
java CLITester -DrollNo = 1 -Dclass = VI -Dname = Mahesh Class: VI Roll No: 1 Name: MaheshAdvertisements