Comfortable mechanism for command line args in Java

Basically, parsing command line arguments is a real pain, as you don’t know in what order they will be passed on; you might also want to provide some guidance to users etc.

As often in, there’s a library for that -> http://args4j.kohsuke.org/

Here’s basically how it works:

1.) Create on An Option class:

    private static class Options {

        @org.kohsuke.args4j.Option(name = "-dir", required = true, usage = "input directory for files")
        private String directory;
    }

2.) Parse the options using the CmdLineParser, parse it and reference your values from the option instance:

        Options options = new Options();
        CmdLineParser parser = new CmdLineParser(options);
        parser.parseArgument(args);
        // this contains the value passed on in args
        String dir = options.directory;

that’s it. You will want to use maven to add args4j:

    <dependency>
	<groupId>args4j</groupId>
	<artifactId>args4j</artifactId>
	<version>2.0.10</version>
    </dependency>
Advertisements
This entry was posted in Uncategorized and tagged , . Bookmark the permalink.

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