Simple way to parse command line arguments in java using Apache Commons CLI

first define Options for application

final Options options = new Options();
options.addOption(“d”, “database”, true, “jdbc URL to database, REQUIRED”);
options.addOption(“u”, “dbuser”, true, “database user name, REQUIRED”);
options.addOption(“p”, “dbpass”, true, “database password, REQUIRED”);
options.addOption(“v”, “verbose”, false, “Enable verbose output, OPTIONAL, default is disabled”);

next parse arguments and check it with options

final org.apache.commons.cli.CommandLineParser parser = new PosixParser();
cmd = parser.parse(options, args);

use boolean verbose = cmd.hasOption(“v”)  to check if parameter was passed in command line

use String user = cmd.getOptionValue(“u”); to get the parameter value

automatically generate the help statement

final HelpFormatter formatter = new HelpFormatter();
final StringBuilder usageSb = new StringBuilder();
usageSb.append(“java -jar my-application.jar [-v] -d <jdbc url> -u <db user> -p <db password>”);
final StringBuilder header = new StringBuilder();
header.append(“Description of the application:\n”);
header.append(“more info on the webpage;);
formatter.printHelp(usageSb.toString(), header.toString(), options,
“\nFor more information please check webpage;);


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.