Java command line argument processing

A nice way to process command line arguments is arg4j (https://args4j.dev.java.net/).

The resulting code will be 10 times better than code using Apache Commons CLI (never use Findbugs/PMD or any other static software analyse tool on Commons CLI and never, really never take a look at the sources! :-/).

Example code and description can be found here. http://weblogs.java.net/blog/kohsuke/archive/2005/05/parsing_command.html

Arg4J takes full use of and supports  Java5 language features (annotations and enums)

public final class Main {

public static void main(String[] args) throws  CmdLineException {
new Main().doMain(args);
}

@Option(name = “-h”, aliases = { “-help” }, usage = “print this message”)
private boolean help = false;

@Option(name = “-i”, required = true, usage = “input from this file”, metaVar = “/path/to/your.class”)
private File in = new File(“.”);

@Option(name = “-o”, required = true, usage = “output to this dir”, metaVar = “/tmp/bin”)
private File out = new File(“.”);

[…]

Parsing is done easily by invoking the Parser:

private void doMain(String[] args) throws CmdLineException {
CmdLineParser parser = new CmdLineParser(this);
parser.setUsageWidth(130);
try {
parser.parseArgument(args);
} catch (CmdLineException e) {
System.err.println(e.getMessage());
showHelpAndExit(parser);
}

Advertisements
This entry was posted in Java, Projects. Bookmark the permalink.

One Response to Java command line argument processing

  1. Pingback: Java command line argument processing — alternative | Peter Fichtner's Blog

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s