Great little library for command line args

I needed to a commandline args to a java program the other day and I did not feel like writing out all the code to do it. There are several very good libraries to parse command line args, so I decided to use jopt-simple.

What made me decide to use it was the nice fluent interface:

OptionParser parser = new OptionParser();
parser.accepts("f", "Json file to process").withRequiredArg().ofType(String.class).describedAs("path to the file");
parser.accepts("b", "Branch to process").withRequiredArg().ofType(String.class).describedAs("Branch name");
parser.accepts("r", "set branch (-b) to release mode").withRequiredArg().ofType(Boolean.class).describedAs("true if the tests need to be run").defaultsTo(false);
parser.acceptsAll(Arrays.asList("h", "?"), "show help").forHelp();

Parsing is done with

parser.parse(args)

Now you can access the options like this:

if (options.has("h"))
{
        parser.printHelpOn(System.err);
        return;
    }
    if (options.has("f"))
    {
        branchList = Branch.readBranchFromFile((String)options.valueOf("f"));
    }
    if (options.has("b"))
    {
        String branchname = (String)options.valueOf("b");
        branchList = new ArrayList<>(Arrays.asList(getBranch(branchname)));
    }
}

So easy :)

comments powered by Disqus
comments powered by Disqus