Commons CLI API - Short Options Example

Q

Where to get a Java example of managing short options with Commons CLI API?

✍: FYIcenter.com

A

Here is good Java example of managing short options with Commons CLI API, ShortOptionTest.java:

// Copyright (c) 2018 FYIcenter.com
import org.apache.commons.cli.Options;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.UnrecognizedOptionException;

public class ShortOptionTest {
   public static void main(String[] args) throws Exception {
       
      // Define a short option: -h
      Options options = new Options();
      options.addOption("h", "Print this help message");
      
      try {
         // Parse options
         CommandLineParser parser = new DefaultParser();
         CommandLine cmd = parser.parse(options, args);
         
         // Process options
         if (cmd.hasOption("h")) {
            help(options);
         }
      } catch (UnrecognizedOptionException e) {
         System.out.println("Invalid options: "+e.getOption());
         help(options);
      }
   }

   public static void help(Options options) {
      // Print options
      HelpFormatter formatter = new HelpFormatter();
      formatter.printHelp("ShortOptionTest", options);
   }
}

You can compile and run it with commons-cli-1.4.jar:

C:\fyicenter>javac -cp C:\fyicenter\commons-cli-1.4\commons-cli-1.4.jar ShortOptionTest.java

C:\fyicenter>java -cp .;C:\fyicenter\commons-cli-1.4\commons-cli-1.4.jar ShortOptionTest -h
usage: ShortOptionTest
 -h   Print this help message
 
C:\fyicenter>java -cp .;C:\fyicenter\commons-cli-1.4\commons-cli-1.4.jar ShortOptionTest -help
Invalid options: -help
usage: ShortOptionTest
 -h   Print this help message

C:\fyicenter>java -cp .;C:\fyicenter\commons-cli-1.4\commons-cli-1.4.jar ShortOptionTest -?
Invalid options: -?
usage: ShortOptionTest
 -h   Print this help message

 

Commons CLI API - Long Options

Commons CLI API - Short Options

Using commons-cli.jar in Java Programs

⇑⇑ FAQ for Apache Commons CLI JAR Library

2018-11-09, 237👍, 0💬