2

I have following code:

options.addOption(OptionBuilder.withLongOpt(SOURCES)
                .withDescription("path to sources")
                .hasArg()
                .withArgName("PATHS")
                .create());
...
CommandLineParser parser = new GnuParser();
line = parser.parse(options, args);
...
System.out.println(line.getOptionValues(SOURCES));

I invoke application with parameters

-sources=path1, path2

in result I see ["path1"]

I want to get both arguments. How can I pass it?

what should I write in command line

gstackoverflow
  • 36,709
  • 117
  • 359
  • 710

2 Answers2

5

Make the argument values space-delimited, rather than comma-delimited:

-source=path1 path2

Also, you need to use .hasArgs() rather than .hasArg() to return more than one argument value. You can also specify .hasArgs(2) for an explicit number of argument values. Here's a working example:

Input: -source=path1 path2

public class Test {

    public static void main(String[] args) {
        Options options = new Options();
        options.addOption(OptionBuilder.withLongOpt("sources").withDescription("path to sources").hasArgs().withArgName("PATHS").create());

        CommandLineParser parser = new GnuParser();
        CommandLine line = null;

        try {
            line = parser.parse(options, args, true);
        } catch (ParseException exp) {
            System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        }

        System.out.println(Arrays.toString(line.getOptionValues("sources")));
    }
}

Output: [path1, path2]

martinez314
  • 12,162
  • 5
  • 36
  • 63
5

If you want to pass an array, you should replace hasArg() with hasArgs() to indicate that the option may have multiple values. Now you can pass them like this:

-sources path1 path2

If you want to be able to pass them comma-separated, you can call withValueSeparator(',') on your OptionBuilder, resulting in code like the following:

options.addOption(OptionBuilder.withLongOpt(SOURCES)
    .withDescription("path to sources")
    .hasArgs()
    .withValueSeparator(',')
    .withArgName("PATHS")
    .create());

Now you can pass them this way:

-sources path1,path2

Keep in mind, however, that space will still be treated as a separator.

izstas
  • 5,004
  • 3
  • 42
  • 56