在此处使用Apache Commons CLI 1.2。我有一个需要 2 个运行时选项的可执行 JAR,fizz
并且buzz
;两者都是需要参数/值的字符串。我希望(如果可能的话)我的应用程序像这样执行:
java -jar myapp.jar -fizz "好吧,那么!" -buzz “现在保重,那么再见!”
在这种情况下,fizz
选项的值将是“ Alrighty,then! ”等。
这是我的代码:
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;
}
}
}
当我运行它时,我得到以下输出:
嘶嘶声是:空
我需要对我的代码做些什么,以便我的应用程序可以按我想要的方式调用?或者我最接近它的地方是什么?
加分:OptionBuilder
如果有人可以向我解释'swithArgName(...)
和参数之间的区别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");