Apache Commons CLI - Quick Guide



Apache Commons CLI - Overview

The Apache Commons CLI are the components of the Apache Commons which are derived from Java API and provides an API to parse command line arguments/options which are passed to the programs. This API also enables to print help related to options available.

Command line processing comprises of three stages. These stages are explained below −

  • Definition Stage
  • Parsing Stage
  • Interrogation Stage

Definition Stage

In definition stage, we define the options that an application can take and act accordingly. Commons CLI provides Options class, which is a container for Option objects.

// create Options object
Options options = new Options();

// add a option
options.addOption("a", false, "add two numbers");

Here we have added an option flag a, while false as second parameter, signifies that option is not mandatory and third parameter states the description of option.

Parsing Stage

In parsing stage, we parse the options passed using command line arguments after creating a parser instance.

//Create a parser
CommandLineParser parser = new DefaultParser();

//parse the options passed as command line arguments
CommandLine cmd = parser.parse( options, args);

Interrogation Stage

In Interrogation stage, we check if a particular option is present or not and then, process the command accordingly.

//hasOptions checks if option is present or not
if(cmd.hasOption("a")) {
   // add the two numbers
} else if(cmd.hasOption("m")) {
   // multiply the two numbers
}

Apache Commons CLI - Environment Setup

This chapter will guide you on how to prepare a development environment to start your work with Apache Commons IO. It will also teach you how to set up JDK on your machine before you set up Apache Commons CLI −

Setup Java Development Kit (JDK)

You can download the latest version of SDK from Oracle's Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively.

If you are running Windows and have installed the JDK in C:\jdk-24, you would have to put the following line in your C:\autoexec.bat file.

set PATH=C:\jdk-24;%PATH% 
set JAVA_HOME=C:\jdk-24

Alternatively, on Windows NT/2000/XP, you will have to right-click on My Computer, select Properties → Advanced → Environment Variables. Then, you will have to update the PATH value and click the OK button.

On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk-24 and you use the C shell, you will have to put the following into your .cshrc file.

setenv PATH /usr/local/jdk-24/bin:$PATH 
setenv JAVA_HOME /usr/local/jdk-24

Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, you will have to compile and run a simple program to confirm that the IDE knows where you have installed Java. Otherwise, you will have to carry out a proper setup as given in the document of the IDE.

Popular Java Editors

To write your Java programs, you need a text editor. There are many sophisticated IDEs available in the market. But for now, you can consider one of the following −

  • Notepad − On Windows machine, you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad.

  • Netbeans − It is a Java IDE that is open-source and free, which can be downloaded from www.netbeans.org/index.html.

  • Eclipse − It is also a Java IDE developed by the eclipse open-source community and can be downloaded from www.eclipse.org.

Download Common IO Archive

Download the latest version of Apache Common IO jar file from commons-cli-1.10.0-bin.zip. At the time of writing this tutorial, we have downloaded commons-cli-1.10.0-bin.zip and copied it into C:\>Apache folder.

OS Archive name
Windows commons-cli-1.10.0-bin.zip
Linux commons-cli-1.10.0-bin.tar.gz
Mac commons-cli-1.10.0-bin.tar.gz

Set Apache Common IO Environment

Set the APACHE_HOME environment variable to point to the base directory location where Apache jar is stored on your machine. Assuming, we've extracted commons-cli-1.10.0-bin.zip in Apache folder on various Operating Systems as follows.

OS Output
Windows Set the environment variable APACHE_HOME to C:\Apache
Linux export APACHE_HOME=/usr/local/Apache
Mac export APACHE_HOME=/Library/Apache

Set CLASSPATH Variable

Set the CLASSPATH environment variable to point to the Common IO jar location. Assuming, you have stored commons-cli-1.10.0-bin.zip in Apache folder on various Operating Systems as follows.

OS Output
Windows Set the environment variable CLASSPATH to %CLASSPATH%;%APACHE_HOME%\commons-cli-1.10.0-bin.jar;.
Linux export CLASSPATH=$CLASSPATH:$APACHE_HOME/commons-cli-1.10.0-bin.jar:.
Mac export CLASSPATH=$CLASSPATH:$APACHE_HOME/commons-cli-1.10.0-bin.jar:.

Apache Commons CLI - First Application

Introduction

In order to create a console based application using Apache Commons CLI, we define stages.

  • Definition Stage − Used to define the options used as command line arguments.

  • Parsing Stage − Used to define the parser and parse the arguments using options.

  • Interrogation Stage − Used to check the arguments passed and perform the business logic accordingly.

Definition Stage

Define the Options to be used as command line arguments.

// create Options object
Options options = new Options();
      
// add option "-a"
options.addOption("a", false, "add numbers");

Parsing Stage

Define the CommandLineParser. We're using DefaultParser object here.

// Create a parser
CommandLineParser parser = new DefaultParser();

// parse the options passed as command line arguments
CommandLine cmd = parser.parse( options, args);

Interrogation Stage

Check the options passed during execution and act accordingly.

// hasOptions checks if option is present or not
if(cmd.hasOption("a")) {
   System.out.println("Sum of the numbers: " + getSum(args));
} else if(cmd.hasOption("m")) {
   System.out.println("Multiplication of the numbers: " + getMultiplication(args));
}

Example - Creating First Console Application

Let's create a sample console based application, whose purpose is to get either sum of passed numbers or multiplication of passed numbers based on the options used.

CLITester.java

package com.tutorialspoint;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

public class CLITester {
   public static void main(String[] args) throws ParseException {
      // ***Definition Stage***
      // create Options object
      Options options = new Options();
      
      // add option "-a"
      options.addOption("a", false, "add numbers");
      
      // add option "-m"
      options.addOption("m", false, "multiply numbers");

      // ***Parsing Stage***
      // Create a parser
      CommandLineParser parser = new DefaultParser();

      // parse the options passed as command line arguments
      CommandLine cmd = parser.parse( options, args);

      // ***Interrogation Stage***
      // hasOptions checks if option is present or not
      if(cmd.hasOption("a")) {
         System.out.println("Sum of the numbers: " + getSum(args));
      } else if(cmd.hasOption("m")) {
         System.out.println("Multiplication of the numbers: " + getMultiplication(args));
      }
   }
   public static int getSum(String[] args) {
      int sum = 0;
      for(int i = 1; i < args.length ; i++) {
         sum += Integer.parseInt(args[i]);
      }
      return sum;
   }
   public static int getMultiplication(String[] args) {
      int multiplication = 1;
      for(int i = 1; i < args.length ; i++) {
         multiplication *= Integer.parseInt(args[i]);
      }
      return multiplication;
   }
}

Output

Run the file, while passing -a as option and numbers to get the sum of the numbers as result −

java CLITester -a 1 2 3 4 5
Sum of the numbers: 15

Run the file, while passing -m as option and numbers to get the multiplication of the numbers as result −

java CLITester -m 1 2 3 4 5
Multiplication of the numbers: 120

Apache Commons CLI - Option Properties

Option object is used to represent the Option passed to command line program. Following are various properties that an Option object possess.

Option Object Properties

Sr.No Name (Type) &amps; Description
1

opt (String)

Identification string of the Option.

2

longOpt (String)

Alias and more descriptive identification string.

3

description (String)

Description of the function of the option.

4

required (boolean)

Flag to check whether the option must appear on the command line.

5

arg (boolean)

Flag to check whether the option takes an argument.

6

args (boolean)

Flag to check whether the option takes more than one argument.

7

optionalArg (boolean)

Flag to check whether the option's argument is optional.

8

argName (String)

Name of the argument value for the usage statement.

9

valueSeparator (char)

The character value used to split the argument string.

10

type (Object)

Argument type.

11

value (String)

Option value.

12

values (String[])

Values of the option.

Example - Usage of Option Properties - Without Mandatory Argument

Let's create a sample console based application, whose purpose is to get sum of passed numbers based on the option used.

CLITester.java

package com.tutorialspoint;

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 {
      // create Options object
      Options options = new Options();

      // Create Option object
      Option addOption = new Option("a", "Add Numbers");
      
      // argument is required
      addOption.setRequired(true);
      
      // add option "-a"
      options.addOption(addOption);
      
      // ***Parsing Stage***
      // Create a parser
      CommandLineParser parser = new DefaultParser();

      // parse the options passed as command line arguments
      CommandLine cmd = parser.parse( options, args);

      // ***Interrogation Stage***
      // hasOptions checks if option is present or not
      if(cmd.hasOption("a")) {
         System.out.println("Sum of the numbers: " + getSum(args));
      } 
   }
   public static int getSum(String[] args) {
      int sum = 0;
      for(int i = 1; i < args.length ; i++) {
         sum += Integer.parseInt(args[i]);
      }
      return sum;
   }   
}

Output

Run the file, without passing -a as option and CLI will throw MissingOptionException −

Exception in thread "main" org.apache.commons.cli.MissingOptionException: Missing required option: a
	at org.apache.commons.cli.DefaultParser.checkRequiredOptions(DefaultParser.java:344)
	at org.apache.commons.cli.DefaultParser.parse(DefaultParser.java:770)
	at org.apache.commons.cli.DefaultParser.parse(DefaultParser.java:815)
	at org.apache.commons.cli.DefaultParser.parse(DefaultParser.java:797)
	at org.apache.commons.cli.DefaultParser.parse(DefaultParser.java:776)
	at com.tutorialspoint.CLITester.main(CLITester.java:29)

Run the file, while passing -a as option and numbers to get the sum of the numbers as result −

java CLITester -a 1 2 3 4 5
Sum of the numbers: 15

Apache Commons CLI - Boolean Option

Overview

A boolean option is represented on a command line by its presence. For example, if option is present, then its value is true, otherwise, it is considered as false. Consider the case, where we are printing current date and if -t flag is present. Then, we will print time too.

Define an Optional Argument

Options options = new Options();
// pass required as false to make option as non-mandatory
options.addOption("t", false, "display time");

Check if Argument is passed then act accordingly

if(cmd.hasOption("t")) {
   System.out.print(" " + hour + ":" + min + ":" + sec);
}

Example - Handling Boolean Option in Command Line Arguments

CLITester.java

package com.tutorialspoint;

import java.util.Calendar;
import java.util.Date;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
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();
      options.addOption("t", false, "display time");
      
      CommandLineParser parser = new DefaultParser();
      CommandLine cmd = parser.parse( options, args);

      Calendar date = Calendar.getInstance();
      int day = date.get(Calendar.DAY_OF_MONTH);
      int month = date.get(Calendar.MONTH);
      int year = date.get(Calendar.YEAR);

      int hour = date.get(Calendar.HOUR);
      int min = date.get(Calendar.MINUTE);
      int sec = date.get(Calendar.SECOND);

      System.out.print(day + "/" + month + "/" + year);
      if(cmd.hasOption("t")) {
         System.out.print(" " + hour + ":" + min + ":" + sec);
      }
   }
}

Output

Run the file without passing any option and see the result −

java CLITester
27/7/2025

Run the file, while passing -t as option and see the result −

java CLITester -t
27/7/2025 4:40:11

Apache Commons CLI - Argument Option

Overview

An Argument option is represented on a command line by its name and its corresponding value. For example, if option is present, then user has to pass its value.

java CLITester --logFile test.log

Then the value of logFile option should be test.log passed as argument which we can use later to create a log file and store information.

Read the argument value using getOptionValue() method.

// has the logFile argument been passed?
if(cmd.hasOption("logFile")) {
   //get the logFile argument passed
   System.out.println( "File name passed: " + cmd.getOptionValue( "logFile" ) );
}

Example - Reading Arguments Based on Option passed

In this example, we're printing name of the log file passed with the argument option logFile.

CLITester.java

package com.tutorialspoint;

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 logfile = Option.builder()
         .longOpt("logFile")
         .argName("file" )
         .hasArg()
         .desc("use given file for log" )
         .get();

      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( "File name passed: " + 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
File name passed: test.log

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

Apache Commons CLI - Usage Example

Overview

Apache Commons CLI provides HelpFormatter class to print the usage guide of command line arguments. Consider the following usage to be printed when we used the application without passing any argument.

java CLITester
usage: CLITester [-g] [-n <arg>] [-p]

Define the Options

options.addOption("p", "print", false, "Send print request to printer.")
   .addOption("g", "gui", false, "Show GUI Application")
   .addOption("n", true, "No. of copies to print");

Print the usage using HelpFormatter

System.out.println("usage: CLITester " + formatter.toSyntaxOptions(options));

Example - Printing usage on command line arguments

In this example, we're printing usage using HelpFormatter if no argument is passed.

CLITester.java

package com.tutorialspoint;

import java.io.IOException;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.help.HelpFormatter;

public class CLITester {
   public static void main(String[] args) throws ParseException, IOException {
	
      Options options = new Options();
      options.addOption("p", "print", false, "Send print request to printer.")
         .addOption("g", "gui", false, "Show GUI Application")
         .addOption("n", true, "No. of copies to print");
			
      String header = "Welcome to CLI Application";
      String footer = "Please report issues at https://tutorialspoint.com/issues";

      HelpFormatter formatter = HelpFormatter.builder().get();
	  
      // Create a parser
      CommandLineParser parser = new DefaultParser();

      // parse the options passed as command line arguments
      CommandLine cmd = parser.parse( options, args);

      // hasOptions checks if option is present or not
      if(cmd.hasOption("p")) {
         // do printing
      }
      else if(cmd.hasOption("g")) {
         // show gui
      }else if (cmd.hasOption("n")) {
         // get no. of copies
      }else {
         // print usage
    	  System.out.println("usage: CLITester " + formatter.toSyntaxOptions(options));
      }
   }
}

Output

Run the file, without passing any argument and see the result −

java CLITester 
usage:  CLITester [-g] [-n <arg>] [-p]

Apache Commons CLI - Help Example

Overview

Apache Commons CLI provides HelpFormatter class to print the help guide of command line arguments. Consider the following help to be printed when we used the application without passing any argument.

java CLITester
usage: CLITester
-g,--gui Show GUI Application
-n  No. of copies to print
-p,--print Send print request to printer.

Define the Options

options.addOption("p", "print", false, "Send print request to printer.")
   .addOption("g", "gui", false, "Show GUI Application")
   .addOption("n", true, "No. of copies to print");

Print the help using HelpFormatter

HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("CLITester", options);

Example - Printing help on command line arguments

In this example, we're printing help using HelpFormatter if no argument is passed.

CLITester.java

package com.tutorialspoint;

import java.io.IOException;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.help.HelpFormatter;

public class CLITester {
   public static void main(String[] args) throws ParseException, IOException {
	
      Options options = new Options();
      options.addOption("p", "print", false, "Send print request to printer.")
         .addOption("g", "gui", false, "Show GUI Application")
         .addOption("n", true, "No. of copies to print");
			
      String header = "Welcome to CLI Application";
      String footer = "Please report issues at https://tutorialspoint.com/issues";

      HelpFormatter formatter = HelpFormatter.builder().get();
	  
      // Create a parser
      CommandLineParser parser = new DefaultParser();

      // parse the options passed as command line arguments
      CommandLine cmd = parser.parse( options, args);

      // hasOptions checks if option is present or not
      if(cmd.hasOption("p")) {
         // do printing
      }
      else if(cmd.hasOption("g")) {
         // show gui
      }else if (cmd.hasOption("n")) {
         // get no. of copies
      }else {
         // print help
         formatter.printHelp("CLITester", header, options, footer, true);
      }
   }
}

Output

Run the file, without passing any argument and see the result −

java CLITester usage:  CLITester [-g] [-n <arg>] [-p]

 Welcome to CLI Application

   Options       Since              Description          
 -p, --print      --       Send print request to printer.
 -g, --gui        --       Show GUI Application          
 -n <arg>   --       No. of copies to print        

 Please report issues at https://tutorialspoint.com/issues
Advertisements