November 05, 2009

Java CLI

« CSV File Handling in Java | Main | JSTL Example »
Sometimes you have to parse the command line arguments. For example you want to implement a daemon service application. The service characteristics should be defined in the form of command line parameters. In Java you can use the Apache Common CLI library. This library enables an easy way to interprets command line parameters. It supports all interesting interpretation styles.

  • GNU style -> psql --username --hostname ...
  • POSIX style -> ls -la ...
  • Java style -> mvn -Dmaven.skip.test -Dprofile=testing ...
The following example describes an impl
package org.developers.blog.experiments;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser;

/**
 * CLI!
 *
 */
public class CLI {

    public static void main(String[] args) throws Exception {

        Options options = new Options();
        // show the current date
        // first the opt name, second has args, third description
        options.addOption("displayname", true, "display my name");
        options.addOption("help", false, "help");

        // interpretation of the options based on posix structure
        CommandLineParser parser = new PosixParser();
        CommandLine cmd = parser.parse( options, args);
        if(cmd.hasOption("displayname")) {
            System.out.println("Your name is: " + cmd.getOptionValue("displayname"));
        } 
        if (cmd.hasOption("help")) {
            // automatically generate the help statement
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp( "help", options );
        }
    }
}
Possile results are:
(1) {command} --help
usage: help
 -displayname    display my name
 -help                help
(2) {command} --displayname=Rafael
Your name is: Rafael
Regards
Rafael

Technorati Tags:

Posted by rafael.sobek at 10:56 PM in Java

 

[Trackback URL for this entry]

Your comment:

(not displayed)
 
 
 

Live Comment Preview:

 
« November »
SunMonTueWedThuFriSat
1234567
891011121314
15161718192021
22232425262728
2930