See how the open source JSAP differs from other CLI libraries. Heavily used in Groovy, it brings flexibility that makes it good for simple or complex use cases.
JSAP ( Java Simple Argument Parser) 2.1 is the focus of this twentieth post in this series on processing command line arguments from Java. The JSAP page describes the library’s reason for existence: “I found several parsers on the Internet, all of which handled switches, but none of which had the versatility I wanted in terms of return types and configuration files.”
JSAP offers quite a bit of flexibility at the normal cost of some complexity. Fortunately, JSAP provides a class called SimpleJSAP that makes it easier to accomplish simple tasks with JSAP. The JSAP documentation articulates it this way, “If you want to minimize the amount of code handling the command line, JSAP offers a SimpleJSAP that does most of the work for you.” The next code listing demonstrates using SimpleJSAP in a single (albeit verbose) statement to define the expected command line options.
For the above code listing, I used static imports to reduce the verbosity of this “definition” code. These can be seen in the full code listing available on GitHub. The code above defines the two options being used in all of the posts in their series on libraries used to parse command line arguments in Java: file path/name and verbosity. The single characters ‘f’ and ‘v’ are the short option names and the long option names follow them in their respective calls ( file and verbose). Note that the “definition” of command line arguments can be configured via XML as well, though that is not demonstrated here.
The “parsing” stage is accomplished in JSAP with another single statement in which an invocation of the parse(String[]) method on the instance of SimpleJSAP returns an instance of JSAPResult .
JSAP’s “interrogation” stage is accomplished with calls on the instance of JSAPResult returned by the parse method as demonstrated in the next code listing.
JSAP will generate automatic usage and help statements. The next code listing demonstrates use of the SimpleJSAP.messagePrinted() method to determine if some time of parsing error occurred and then using the SimpleJSAP.getHelp() message to access the automatically generated “help” message.
The next two screen snapshots demonstrate execution of the code examples shown in this post using JSAP. The first image depicts the usage statement printed when the required -f / –file flag is not provided. The second image depicts normal behavior of the example code based on JSAP.
There are characteristics of JSAP to consider when selecting a framework or library to help with command-line parsing in Java.
JSAP seems to be one of the more popular of the older Java-based command-line parsing libraries. It’s relatively easy to use for basic functionality like that demonstrated in this post, but also offers additional flexibility and customizability for more complex needs.

Continue reading...