Java – Read/Parse Command Line Arguments/Options

Java – Read/Parse Command Line Arguments/Options

Maven Dependency :

<dependency>
    <groupId>commons-cli</groupId>
    <artifactId>commons-cli</artifactId>
    <version>1.2</version>
</dependency>

Sample Java Program :

package test;

import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public class Test
{
    public static void main(String[] args) {

        //Define Options
        Options options = new Options();

        //Option Name - option1
        //Has input value - true
        options.addOption("option1", true, "Option 1 Description");

        //Option Name - option2
        //Has input value - false
        options.addOption("option2", false, "Option 2 Description");

        CommandLineParser parser = new BasicParser();
        CommandLine cmd = null;

        try {
            cmd = parser.parse(options, args);
        } catch (ParseException e1) {
            e1.printStackTrace();
        }

        System.out.println(cmd.hasOption("option1"));
        System.out.println(cmd.hasOption("option2"));

        System.out.println(cmd.getOptionValue("option1"));
        System.out.println(cmd.getOptionValue("option2"));

    }
}

Output :

Consider we execute the sample Java program with following arguments

java Test -option1 option1Value -option2

true
true
option1Value
null

option2 value is null because it does not takes input values which is defined using the Options class.

[ YOU MAY ALSO LIKE ]

Leave a Reply