问题
I need a library which can take command line options of the form java -jar --aaa=a --bbb=b ---ccc=c
and return an array whose values can be accessed as argsArray['aaa'], argsArray['bbb']
etc.
Is there some library with examples to do this?
回答1:
A great parser for command line options in Java is the Apache Commons CLI.
Options can have arguments or not, can be optional or required, and you can set up descriptions for each for usage help. A brief example usage:
public static void main(String[] args) {
Options options = new Options();
try {
options.addOption(OptionBuilder.withArgName("help").hasArgs(0).withDescription("Prints this help message.").isRequired(false).create("h"));
options.addOption(OptionBuilder.withArgName("debug logging").hasArgs(0).withDescription("Enable debug logging").isRequired(false).create("1"));
CommandLineParser parser = new PosixParser();
CommandLine cmd = parser.parse(options, args);
if (cmd.hasOption("h")) {
new HelpFormatter().printHelp(400, "load_page_spool.sh", "OPTIONS", options, "Loads crawl data from pages pool, updating FRONTIER, HISTORY and PageTable", true);
return;
}
....
} catch (MissingOptionException e) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("LoadPageSpool", options);
}
}
回答2:
Try Apache Commons CLI.
Another simple solution might be the helper class presented in this article.
回答3:
If you keep them in a specific order you can access them from the string array that is the parameter for the main method.
http://download.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html
回答4:
Another option to parse command lines would be jcommander. I haven't used it myself but the examples on the website look good and easy to use.
来源:https://stackoverflow.com/questions/6584332/is-there-a-library-to-parse-java-command-line-options-into-an-associative-array