Here is an example code using apache CommandLineParser
public class Foo {
public static void main(final String[] args) throws Exception {
Options options = new Options();
options.addOption("x",
true, "comment for param x");
options.addOption("y",
true, "comment for param y");
CommandLine commandLine = null;
CommandLineParser parser = new PosixParser();
try {
commandLine = parser.parse(options, args);
} catch (ParseException e) {
throw new RuntimeException("Error parsing arguments!");
}
if (!commandLine.hasOption("x")) {
throw new IllegalArgumentException("x"
+ " option is missing!");
}
String numberOfColumns = commandLine.getOptionValue("x");
:
:
}
JUNIT test code:
@Test
public void testFoo() throws Exception {
args = new String[2];
args[0] = "x" + "=" + "hello";
args[1] = "y" + "=" + "world";
Foo.main(args);
}
My problem/question:
CommandLineParser keeps complaining that "x option is missing!". So I believe, the way I am passing the parameter and its values to command line parser is wrong. I tried other ways as well.
args[0] = "-x" + "=" + "hello";
args[1] = "-y" + "=" + "world";
and also
args[0] = "x"
args[1] = "hello";
args[2] = "y"
args[3] = "world";
Can some one, tell me the correct format to pass the arguments and its values so as to succeed?
Thanks in advance.
As far as I know the arguments must start with a minus.
args[0] = "-x";
args[1] = "hello";
args[2] = "-y";
args[3] = "world";