Java CLI : Cant parse arguments

标签 java command-line-interface apache-commons

我正在尝试将命令行参数解析为

Options options = new Options();
        options.addOption("c", "count", false, "number of message to be generated");
        options.addOption("s", "size", false, "size of each messages in bytes");
        options.addOption("t", "threads", false, "number of threads");
        options.addOption("r", "is random", false, "is random");
        CommandLine cli = new DefaultParser().parse(options, args);

        int count = Integer.parseInt(cli.getOptionValue("c", "20000000"));
//        int count = Integer.parseInt(cli.getOptionValue("c", "100"));
        int recordSize = Integer.parseInt(cli.getOptionValue("s", "512"));
        int threads = Integer.parseInt(cli.getOptionValue("t","4"));
        boolean isRandom = Boolean.valueOf(cli.getOptionValue("r", "true"));
        System.out.println(" threads "+threads);
        System.out.println(" count "+count);

我在 Eclipse 中运行它

t 6 c 7

但我总是得到

threads 4
count 20000000

我错过了什么?

最佳答案

当选项带有参数时,您应该对 addOption 方法使用 true。来自 Javadoc:

  • @param hasArg flag signally if an argument is required after this option
    options.addOption("c", "count", true, "number of message to be generated");
    options.addOption("s", "size", true, "size of each messages in bytes");
    options.addOption("t", "threads", true, "number of threads");
    options.addOption("r", "is random", false, "is random");

是的,对于短选项规范(例如 -t 4)需要一个前导 -,对于短选项规范需要一个前导 --长选项规范(例如 --threads 4)。

关于Java CLI : Cant parse arguments,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37466071/

相关文章:

php - 如何通过 composer 为 PHP CLI 提供脚本(独立和依赖)

javascript - 咕噜声,类型错误 : Object has no method 'Split'

java - Apache commons CLI - 重复选项

java - 如何通过 FTP 下载文本文件并将内容读取为字符串

java - Java 中的 println 语句阻塞了线程

java - 如何组合 3 对 RDD

java - 随机查询多个表,有限制

java - 使用具有安全性的 spring mvc 时,为匿名用户存储一些数据的最佳方法是什么?

docker - 如何在安装了 Grafana 的 docker 上使用 grafana-cli?

java - PropertyUtils 性能