0

僅供參考:我在Windows計算機上運行此Java程序。我相信這很重要。在指定附加值時Java Apache Common CLI雙精靈選項失敗

基本上,我有一個問題,指定一個值到雙連字符的選項。單連字選項正常工作。

import org.apache.commons.cli.*; 

public class Test { 
    public static void main(String[] args) throws ParseException { 
     String[] arguments = new String[] { "--input file.txt" }; 

     // create the Options 
     Options options = new Options(); 
     options.addOption("i", "input", false, "Specify the input file."); 

     // Create the parser 
     CommandLineParser parser = new GnuParser(); 

     // Parse the command line 
     CommandLine cmd = parser.parse(options, arguments); 
    } 
} 

程序失敗,錯誤:

Exception in thread "main" org.apache.commons.cli.UnrecognizedOptionException: Unrecognized option: --input file.txt

如果我指定的參數作爲-i file.txt,沒有錯誤。如果參數是--input,也沒有錯誤。爲什麼雙連字符選項不接受任何值?它與解析器有關,還是我在Windows機器上運行它?

我在這裏做錯了什麼?任何幫助,將不勝感激。

非常感謝。

回答

1

問題是你如何你的樣品在指定THA參數,而不是

String[] arguments = new String[] { "--input file.txt" }; 

你需要指定

String[] arguments = new String[] { "--input", "file.txt" }; 

分析器希望得到的參數它們Java提供的方式在main()方法中,在空白處分隔,否則指示解析器處理選項「input file.txt」,即它將整個字符串視爲選項的名稱。

+0

非常感謝。有趣。爲什麼程序不會在'-i file.txt'中出現錯誤,而是用'--input file.txt'? – user3621633 2015-04-03 13:35:27

+0

不確定,但解析器可能以某種方式處理這個短期選項,但可能不是長期選項。 – centic 2015-04-03 16:04:24