Reputation: 3409
I am trying to use Java cli commanlineparser to parse the follwing arguments,
java -OC:\mydirectory -NMyfile
Option -O is for directory and -N is for the name of file.
I have been looking online but couldnt find a good example and this is what I am trying to do,
Option option = new Option()
option.addOpton("O",true, "output directory)
option.addOpton("N",true, "file name)
...
CommandLineParser parser = new BasicParser();
...
if (cmd.hasOption("O")
...
Basically, I am trying to add multiple options and be able to parse them. Is this correct way to run the program with above options?
Thanks.
Upvotes: 3
Views: 4755
Reputation: 6229
Try the following:
...
Option opt1 = OptionBuilder.hasArgs(1).withArgName("output directory")
.withDescription("This is the output directory").isRequired(true)
.withLongOpt("output").create("O");
Option opt2 = OptionBuilder.hasArgs(1).withArgName("file name")
.withDescription("This is the file name").isRequired(true)
.withLongOpt("name").create("N")
Options o = new Options();
o.addOption(opt1);
o.addOption(opt2);
CommandLineParser parser = new BasicParser();
try {
CommandLine line = parser.parse(o, args); // args are the arguments passed to the the application via the main method
if (line.hasOption("output") {
//do something
} else if(line.hasOption("name") {
// do something else
}
} catch(Exception e) {
e.printStackTrace();
}
...
Also, you should leave a blank space between the argument and the value in the command line.
Upvotes: 1