在這裏使用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