Java Cli命令行分析器

Java Cli命令行分析器,java,command-line-arguments,Java,Command Line Arguments,我正在尝试使用Java cli commanlineparser来解析以下参数 java -OC:\mydirectory -NMyfile 选项-O表示目录,-N表示文件名 我一直在网上寻找,但找不到一个好的例子,这就是我想做的 Option option = new Option() option.addOpton("O",true, "output directory) option.addOpton("N",true, "file name) ... CommandLineParser

我正在尝试使用Java cli commanlineparser来解析以下参数

java -OC:\mydirectory -NMyfile
选项-O表示目录,-N表示文件名

我一直在网上寻找,但找不到一个好的例子,这就是我想做的

Option option = new Option()
option.addOpton("O",true, "output directory)
option.addOpton("N",true, "file name)
...
CommandLineParser parser = new BasicParser();
...
if (cmd.hasOption("O")
...
基本上,我正在尝试添加多个选项并能够解析它们。使用上述选项运行程序是否正确

谢谢。

尝试以下方法:

...
Option opt1 = OptionBuilder.hasArgs(1).withArgName("output directory")
    .withDescription("This is the output directory").isRequired(true)
    .withLongOpt("output").create("O");

Option opt2 = OptionBuilder.hasArgs(1).withArgName("file name")
    .withDescription("This is the file name").isRequired(true)
    .withLongOpt("name").create("N")

Options o = new Options();
o.addOption(opt1);
o.addOption(opt2);
CommandLineParser parser = new BasicParser();

try {
  CommandLine line = parser.parse(o, args); // args are the arguments passed to the  the application via the main method
  if (line.hasOption("output") {
     //do something
  } else if(line.hasOption("name") {
     // do something else
  }
} catch(Exception e) {
  e.printStackTrace();
}
...

另外,您应该在参数和命令行中的值之间留一个空格。

您试过了吗?有什么问题吗?您是在使用apache commons cli库还是在尝试自己实现它?是的,我正在使用apache cli。我得到了“不一致的例外”