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);
}
4

1 回答 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 [选项] [文件]
 -h,--help 打印用法
 -r,--recurse 递归子目录
 -R 与 --recurse 相同
 -v,--version 在详细设置为高的情况下运行
于 2014-07-19T16:19:39.303 回答