【问题标题】:Synonyms when parsing command line using commons-cli使用 commons-cli 解析命令行时的同义词
【发布时间】:2014-09-08 10:45:00
【问题描述】:

我正在尝试使用 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);
}

【问题讨论】:

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


    【解决方案1】:

    此选项目前不作为 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 运行时详细程度设置为高

    【讨论】:

      猜你喜欢
      • 2023-03-22
      • 2011-03-19
      • 1970-01-01
      • 1970-01-01
      • 2012-07-27
      • 1970-01-01
      • 2011-08-28
      • 1970-01-01
      • 2018-12-27
      相关资源
      最近更新 更多