在这里使用Apache Commons CLI 1.2。我有一个可执行JAR需要2个运行时选项,fizz
和buzz
;两者都是需要参数/值的字符串。我会像(如果可能的话),我的应用程序可以像这样执行:Commons CLI不尊重我的命令行安装
Java的罐子myapp.jar -fizz “Alrighty的话!” “现在保重,再见!”
在这种情况下,对于fizz
选项的值将是 “Alrighty,然后!” 等
这里是我的代码:
public class MyApp {
private Options cmdLineOpts = new Options();
private CommandLineParser cmdLineParser = new GnuParser();
private HelpFormatter helpFormatter = new HelpFormatter();
public static void main(String[] args) {
MyApp myapp = new MyApp();
myapp.processArgs(args);
}
private void processArgs(String[] args) {
Option fizzOpt = OptionBuilder
.withArgName("fizz")
.withLongOpt("fizz")
.hasArg()
.withDescription("The fizz argument.")
.create("fizz");
Option buzzOpt = OptionBuilder
.withArgName("buzz")
.withLongOpt("buzz")
.hasArg()
.withDescription("The buzz argument.")
.create("buzz");
cmdLineOpts.addOption(fizzOpt);
cmdLineOpts.addOption(buzzOpt);
CommandLine cmdLine;
try {
cmdLine = cmdLineParser.parse(cmdLineOpts, args);
// Expecting to get a value of "Alright, then!"
String fizz = cmdLine.getOptionValue("fizz");
System.out.println("Fizz is: " + fizz);
} catch(ParseException parseExc) {
helpFormatter.printHelp("myapp", cmdLineOpts, true);
throw parseExc;
}
}
}
当我运行此我得到以下输出:
Fizz是:null
我需要对我的代码做些什么才能以我想要的方式调用我的应用程序?或者我可以最接近它的是什么?
加分点:如果有人能向我解释了OptionBuilder
的withArgName(...)
,withLongOpt(...)
和create(...)
参数之间的差别,正如我在相同的值正在通过为他们所有,像这样:
Option fizzOpt = OptionBuilder
.withArgName("fizz")
.withLongOpt("fizz") } Why do I have to pass the same value in 3 times to make this work?!?
.create("fizz");
1)您的代码不编译(一人失踪分号,没有宣布例外)。 2)对我来说它有效。我得到了预期的'Fizz是:好吧,那么!'。 – Seelenvirtuose
谢谢@Seelenvirtuose(+1) - 对分号(复制n粘贴错误)感到抱歉,我添加了它。你说它适合你吗?你能粘贴你正在使用的确切的命令行调用吗?再次感谢! – smeeb