Sunday, April 11, 2010

Process the command line with CLI in Java, common CLI example

CLI (=Command Line Interface)

How many times have you written a Java application and had had to rewrite a new way of specifying the input parameters to your application? Wouldn't it be nice if there were one single interface to the way you define the input parameters (mandatory vs. numbers vs. Boolean, etc.), parse these parameters (according to a set of rules), interrogate, and decide the path that your application will take? CLI is the answer.

To run this example, needs commons-cli-1.0.jar in the CLASSPATH. YOu can download from here

Refer of this tutorial.

In CLI, each parameter that you want to specify on the command line is an Option. Create an Options object, add individual Option objects to it, then use the CLI-supplied methods to parse the user's input parameters. An Option might require the user to input a value as well; for example, if the name of a file is required. In such a case, the Option must be created where this is explicitly specified.

Create your Options:

Options options = new Options();
options.addOption("n", true, "[name] your name");

2nd way is by creating an Option and then adding it
Option timeOption = new Option("t", false, "current time");

The addOption() method has three parameters.

1. The first parameter is a java.lang.String that represents the option (That would be given by user with - like -t or -n during execution of code).

2. The second parameter is a boolean that specifies whether the option requires an argument or not. For example -n Nik, here I gave Nik with -n because n is defined as true, if I will not give name then it would not be accept. For -t, no need to supply any argument as it is false. Even though if you give any argument, it would not be accept means it would be ignore that extra argument. In the case of a boolean option (sometimes referred to as a flag) an argument value is not present so false is passed.

3. The third parameter is the description of the option. This description will be used in the usage text of the application. When you will not give proper argument that time it will show like help command.

CommandLineParser parser = new PosixParser();
CommandLine cmd = parser.parse( options, args);

The parse methods of CommandLineParser are used to parse the command line arguments. The PosixPaser is great when you need to handle options that are one character long, like the t option in this example. Else use BasicParser for more than one character input.

Now we need to check if the t option is present. To do this we will interrogate the CommandLine object. The hasOption method takes a java.lang.String parameter and returns true if the option represented by the java.lang.String is present, otherwise it returns false.

if(cmd.hasOption("t")) {
// print the date and time
else {
// print the some thing else;

One complete example on CLI :

import org.apache.commons.cli.*;

public class CLIDemo{

public static void main(String args[]){
Options options = new Options();
options.addOption("n", true, "[name] your name");
Option timeOption = new Option("t", false, "current time");

// ** now lets parse the input
CommandLineParser parser = new BasicParser();
CommandLine cmd;
cmd = parser.parse(options, args);
}catch (ParseException pe){ usage(options); return; }

// ** now lets interrogate the options and execute the relevant parts


System.out.println("You have given argument is t");
System.err.println("Date/Time: " + new java.util.Date());

System.out.println("You have given argument is n");
System.err.println("Nice to meet you: " + cmd.getOptionValue('n'));


private static void usage(Options options){

// Use the inbuilt formatter class
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp( "CLIDemo", options );

In the above code, there is no any use to use cmd.getOptionValue('t') with t condition, as t has been setup false and it would be never get any extra argument as n.

How to run CLI example:


D:\JavaTest>java CLIDemo

D:\JavaTest>java CLIDemo -t
You have given argument is t
Date/Time: Sun Apr 11 21:19:50 EEST 2010

D:\JavaTest>java CLIDemo -n
usage: CLIDemo
-n [name] your name
-t current time

D:\JavaTest>java CLIDemo -n Nik
You have given argument is n
Nice to meet you: Nik

D:\JavaTest>java CLIDemo -n "Nik Suman"
You have given argument is n
Nice to meet you: Nik Suman


First time I did not give any argument, so there is no any output.
Second time I gave -t as argument then we got output as per our expectation.
Third time I gave -n. This time, durint parsing the input it got error so execute catch part. Actually -n has been setup with true so we have to have some

extra argument with -n. In catch block we are printing the help format.
Forth time I gave -n With some name, so it worked perfectly.

No comments:

Post a Comment