Search code examples
javacommand-line-interfaceapache-commons

Java CLI : Cant parse arguments


I am trying to parse command line arguments as

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

and i run it in eclipse with

t 6 c 7

but i always get

threads 4
count 20000000

what am i missing?


Solution

  • You should use true for addOption method when the option takes an argument. From the 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");
    

    Yes, and a leading - is required for short option specification (e.g. -t 4) and a leading -- is required for long option specification (e.g. --threads 4).