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

3

我正在尝试使用Apache Commons CLI解析传递给Java命令行实用程序的命令行参数。

是否有一种方法使'-r'和'-R'都表示“递归子目录”,而不必向解析器添加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

目前在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);

}

由此产生的用法信息如下:

用法:cmdline-parser [OPTIONS] [FILES]
 -h,--help 打印使用方法
 -r,--recurse 递归子目录
 -R 与 --recurse 相同
 -v,--version 运行并设置详细程度为高

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接