2012-07-28 14 views
3

我試圖用Java CLI commanlineparser解析follwing參數,Java的CLI的CommandLineParser

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") 
... 

基本上,我想添加多個選項,並可以對其進行解析。這是正確的方式來運行與上述選項的程序?

謝謝。

+0

你試過了嗎?有問題嗎?你是使用apache commons cli庫還是你想自己實現它? – peshkira 2012-07-28 20:21:29

+0

是的,我正在使用Apache Cli。我得到「UnreconginziedOptionExcepton」 – Tony 2012-07-28 20:22:36

回答

1

嘗試以下操作:

... 
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(); 
} 
... 

此外,你應該離開的說法,並在命令行中的值之間的空白。