Friday, May 11, 2012

5 minute intro to parsing command line arguments with jopts simple


Maven:


net.sf.jopt-simple jopt-simple 2.4-rc2          

First you create an OptionParser object 

For example:

OptionParser parser = new OptionParser() {
{
accepts("file").withRequiredArg().ofType(File.class)
.describedAs("nput file");
accepts("date")
.withRequiredArg()
.ofType(Date.class)
.withValuesConvertedBy(
DateConverter
.datePattern("yyyy-MM-dd HH:mm:ss"))
};
    
As you can see, the option argument can be any object that has a string constructor. 

You can print a handy usage via the method

parser.printHelpOn(System.out);

(annoyingly, it throws an IOException). 

Once initialized, you can invoke your OptionsParser on a list of arguments thus:
OptionSet options = parser.parse(args);
Beware, this throws a  runtime exception if unrecognized arguments are passed - you should wrap it in a try catch block.

You can then check if your options are present by invoking

options.has("file")
if this returns true, go ahead and get the argument:
(File) options.valueOf("file")); 
As you specified the argument as a file, it will be retrieved as a file object, the only caveat being that you need to cast it to the right type.

Very useful overall. One thing to note is that the project requires absolutely no dependencies whatsoever (except for those scoped as test). So unlike the bloaty apache type of "utilities" which pull in 5 dozen other dependencies with them, this library is super lightweight.

Link to project page here