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.
(1) {command} --help
Rafael
- GNU style -> psql --username --hostname ...
- POSIX style -> ls -la ...
- Java style -> mvn -Dmaven.skip.test -Dprofile=testing ...
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(2) {command} --displayname=Rafaeldisplay my name -help help
Your name is: RafaelRegards
Rafael
