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