Apache commons-cli can be used for parsing command line arguments that might be supplied to the java program. The program below is a sample-program that uses commons-cli’s CommandLineParser utility to parse the arguments.
import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; public class CommandParserUtility { public static void main(String[] args) { CommandLineParser parser = new BasicParser(); Option helpOption = new Option("help",false," Program Help."); Option authorOption = new Option("author",false," Program Author."); Option userOption = new Option("user",true," Wish User."); Options options = new Options(); options.addOption(authorOption); options.addOption(userOption); options.addOption(helpOption); CommandLine cli = parser.parse(options, args); if(cli.hasOption(helpOption.getOpt())) System.out.println("CommandParserUtility Usage - \n \nCommandParserUtility -user <User Name> [-author (Show Author Name)][-help|h (Show Usage Help)]\n"); else if(cli.hasOption(userOption.getOpt())) System.out.println("Hey "+cli.getOptionValue(userOption.getOpt())+". You are running the CommandParserUtility."); else if(cli.hasOption(authorOption.getOpt())) System.out.println("CommandParserUtility authored by Vageesh."); else System.out.println("CommandParserUtility Usage - \n \nCommandParserUtility -user <User Name> [-author (Show Author Name)][-help|h (Show Usage Help)]\n"); System.exit(0); } }
In the above program, the command line options available are help, user and author.
Option userOption = new Option("user",true," Wish User."); Option helpOption = new Option("help",false," Program Help.");
Specifies that the argument is user and the Boolean value true specifies that the option takes value when used as argument and in case of help/author, the Boolean value of false indicates that it does not take any arguments with it.
cli.hasOption(helpOption.getOpt())
This code returns a Boolean indicating whether one of the specified options was passed as argument to the program. If you need a list of all arguments passed to the program that is not from the specified argument list, then the following code can be used which returns a list of all unprocessed arguments
ArrayList<Object> res = cli.getArgList();
Finally the values specified for a particular argument can be accessed using the command –
cli.getOptionValue (“user”);