3

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.

2
  • have you tried it? Is there a problem? Are you using the apache commons cli library or are you trying to implement it yourself? Commented Jul 28, 2012 at 20:21
  • Yes and I am using apache cli. I am getting "UnreconginziedOptionExcepton" Commented Jul 28, 2012 at 20:22

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.