- 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 - Properties Option
Overview
A Properties option is represented on a command line by its name and its corresponding properties like syntax, which is similar to java properties file. Consider the following example, if we are passing options like -DrollNo = 1 -Dclass = VI -Dname = Mahesh, we should process each value as properties.
java CLITester -DrollNo=1 -Dclass=VI -Dname=Mahesh
Then
rollNo should 1
class as VI
name as Mahesh
Define the Option as Properties Option
Option propertyOption = Option.builder()
.longOpt("D")
.argName("property=value" )
.hasArgs()
.valueSeparator()
.numberOfArgs(2)
.desc("use value for given properties" )
.get();
Read properties using getOptionProperties() method
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"));
}
Example - Reading Arguments as Properties based on Option passed
In this example, we're process each value passed as properties.
CLITester.java
package com.tutorialspoint;
import java.util.Properties;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public class CLITester {
public 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" )
.get();
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: Mahesh
Advertisements