使用commons-cli解析命令行时的同义词

时间:2014-07-17 13:58:31

标签: java command-line command-line-arguments apache-commons-cli

我正在尝试使用apache commons-cli来解析传递给java命令行实用程序的命令行参数。

“-r”和“-R”是否有办法表示“Recurse subdirectories”而不向解析器添加2个选项(这会弄乱使用情况打印输出)。

一些代码:

Options options = new Options();
options.addOption("r", "recurse", false,"recurse subdirectories");
CommandLineParser parser = new BasicParser();
CommandLine cmd = null;

try {
    cmd = parser.parse( options, args);

} catch (ParseException e) {
    e.printStackTrace();
    HelpFormatter formatter = new HelpFormatter();
    formatter.printHelp("readfiles", options);
}

1 个答案:

答案 0 :(得分:0)

此选项目前不存在作为commons-cli的一部分。
现在必须这样做:

public static void main( String[] args )
{
    Options options = new Options();
    options.addOption("v", "version", false, "Run with verbosity set to high")
           .addOption("h", "help", false, "Print usage")
           .addOption("r", "recurse", false, "Recurse subdirectories")
           .addOption("R", false, "Same as --recurse");

    CommandLine cmd = null;
    CommandLineParser parser = new PosixParser();
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    HelpFormatter formatter = new HelpFormatter();
    formatter.printHelp("cmdline-parser [OPTIONS] [FILES]", options);

}

结果使用信息为:

usage: cmdline-parser [OPTIONS] [FILES]
 -h,--help      Print usage
 -r,--recurse   Recurse subdirectories
 -R             Same as --recurse
 -v,--version   Run with verbosity set to high