开发者

Is there a library to parse java command line options into an associative array?

I need a library which can take command line options of the form java -jar --aa开发者_高级运维a=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?


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);
   }


}


Try Apache Commons CLI.

Another simple solution might be the helper class presented in this article.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜