26

I'm using the Apache Commons CLI to handle command line arguments in Java.

I've declared the a and b options and I'm able to access the value using CommandLine.getOptionValue().

Usage: myapp [OPTION] [DIRECTORY]

Options:
-a        Option A
-b        Option B

How do I declare and access the DIRECTORY variable?

Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331
Mridang Agarwalla
  • 43,201
  • 71
  • 221
  • 382

2 Answers2

33

Use the following method:

CommandLine.getArgList()

which returns whatever's left after options have been processed.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
7

It may be better to use another Option (-d) to identify directory which is more intuitive to the user.

Or the following code demonstrates getting the remaining argument list

public static void main(final String[] args) {
    final CommandLineParser parser = new BasicParser();
    final Options options = new Options();
    options.addOption("a", "opta", true, "Option A");
    options.addOption("b", "optb", true, "Option B");

    final CommandLine commandLine = parser.parse(options, args);

    final String optionA = getOption('a', commandLine);
    final String optionB = getOption('b', commandLine);

    final String[] remainingArguments = commandLine.getArgs();

    System.out.println(String.format("OptionA: %s, OptionB: %s", optionA, optionB));
    System.out.println("Remaining arguments: " + Arrays.toString(remainingArguments));
}

public static String getOption(final char option, final CommandLine commandLine) {

    if (commandLine.hasOption(option)) {
        return commandLine.getOptionValue(option);
    }

    return StringUtils.EMPTY;
}
Nauman
  • 301
  • 1
  • 2
  • 1
    To that, I'd add that the HelpFormatter would be used to print the [DIRECTORY] argument: `HelpFormatter formatter = new HelpFormatter();` `formatter.printHelp("myapp [OPTION] [DIRECTORY]", options);` – Blazes Aug 26 '14 at 20:25