2013-08-20 22 views
3

我正在使用Common CLI作爲個人項目。我從文檔中找不到的一件事是,如何執行某個論點來呈現。Apache Common CLI:如何添加參數?

爲了澄清我的問題,我可以定義參數和選項之間的不同,命令:

mycommand file.txt -b 2 

mycommand is the command, 
file.txt is the argument 
-b 2 is the option where 2 is the option value 

共同CLI,我可以添加-B 2爲這樣一個選項:

options.addOption("b", true, "Some message"); 

並採用解析參數:

CommandLineParser commandParser = new GnuParser(); 
CommandLine result = commandParser.parse(options, args) 

,但我怎麼可以指定file.txt的也是必需的?

非常感謝

回答

1

編輯:我不知道你的意思是使目標(不是一個選項)是必要的。

如果使用完全解析方法CommandLineParser.parse(Options, String[], boolean)並將可選標誌設置爲false,則解析器將跳過未知參數。

您可以通過返回的方法getArgs()取回這些數據的String []

然後你可以通過這些字符串,以確保有一個名爲file.txt的

Options options = new Options(); 

options.addOption("b", true, "some message"); 

String[] myArgs = new String[]{"-b","2", "file.txt"}; 
CommandLineParser commandParser = new GnuParser(); 

CommandLine commandline = commandParser.parse(options, myArgs, false); 

System.out.println(Arrays.toString(commandline.getArgs())); 

將打印字符串[file.txt]添加到屏幕。

所以你添加一個額外的檢查通過數組搜索找到所需的任何目標:

boolean found=false; 
for(String unparsedTargets : commandline.getArgs()){ 
    if("file.txt".equals(unparsedTargets)){ 
     found =true; 
    } 
} 
if(!found){ 
    throw new IllegalArgumentException("must provide a file.txt"); 
} 

我同意這是混亂的,但我不認爲CLI提供了一個乾淨的方式來做到這一點。

1

不,目前的API是不可能的,但我認爲如果強制參數名稱EVER file.txt,您可以擴展GnuParser與您自己的Parser.parse()的實現。
否則,如果文件名可以更改,您可以覆蓋Parser.processArgs()(對於不是選項參數,您的文件名,我的意思是)和Parser.processOption()(設置一個標誌表示您找到了有效的選項):如果在設置標誌時輸入Parser.processArgs()你找到了一個無效的無名ARG)

public class MyGnuParser extends GnuParser { 

    private int optionIndex; 
    private String filename; 

    public MyGnuParser() { 
     this.optionIndex = 0; 
     this.filename = null; 
    } 

public CommandLine parse(Options options, String[] arguments, Properties properties) throws ParseException { 
     CommandLine cmdLine = super.parse(options, arguments, properties, false); 
     if(this.filename == null) throw new ParseException(Missing mandatory filename argument); 
    } 

    @Override 
    public void processArgs(Option opt, ListIterator iter) throws ParseException { 
     super.processArgs(opt, item); 
     ++this.optionIndex; 
    } 

    @Override 
    protected void processOption(final String arg, final ListIterator iter) throws ParseException { 
     if(this.optionIndex > 0) { 
     throw new ParseException(non-opt arg must be the first); 
     } 
     if(this.filename != null) { 
     throw new ParseException(non-opt invalid argument); 
     } 
     this.filename = arg; 
     ++this.optionIndex; 
    } 
} 

MyGnuParser p = new MyGnuParser(); 
CommandLine cmdLine = p.parse(options, args, properties); 

p.filename(或cmdLine.getArgs[0]),你可以得到的文件名。

這並不直觀,但使用CLI API我不知道任何其他方式