Tutorials : Using Program Parameters in Java :

2. Parse

Next step is parsing the arguments:

String[] myArgs = 
  { "-file", "data.log", "-user", "hansen", "jensen", "-verbose"};

CommandLineParser parser = new BasicParser();
CommandLine cmd = null;

try {
  cmd = parser.parse(options, myArgs);
} catch (ParseException e) {
  System.out.println("***ERROR: " 
    + e.getClass() + ": " 
    + e.getMessage());
  return; //or System.exit(-1) 
}

The ParseException may be thrown if a required option is missing or an undefined option is found. If CLI throws an Exception then it would be nice to write out the proper syntax of the command. This can be done like this:

} catch (ParseException e) {
  System.out.println("***ERROR: " 
    + e.getClass() + ": " 
    + e.getMessage());
  HelpFormatter formatter = new HelpFormatter();
  formatter.printHelp( "parameters:", options );
  return;
}
  • 3. Interrogate

    The results of the parsing may now be found in the CommandLine object.

    if (cmd.hasOption("file")) 
      System.out.println("file specified: " + 
      cmd.getOptionValue("file"));
    else 
      System.out.println("-file not entered");
    
    if (cmd.hasOption("user")) 
      System.out.println("user specified: " + 
      Arrays.asList(cmd.getOptionValues("user")));
    else 
      System.out.println("-users not entered");
    
    if (cmd.hasOption("verbose")) 
      System.out.println("verbose specified: " + 
      cmd.getOptionValue("verbose"));
    else 
      System.out.println("-verbose not entered");
    

    If the rest of the program is coded and then run you will see this printed out:

    file specified: data.log
    user specified: [hansen, jensen]
    verbose specified: null
    

    The "null" value shows that the "verbose" option does not take any arguments.

    Warning: CLI also stores the results of the parsing in the Option objects, so don't reuse an object or parse the same object twice.

    Let me finish by mentioning a few useful features in CLI:

  • an option may have both a short name and a long name
  • you may specify arguments without preceding them with specific names (use getArgs to get the arguments from the CommandLine object). The sequence of such arguments is therefore important.
  • you may also specify key-value pairs in java property-style: key=value. An example is given later on in the article.

    Use the JavaDoc to see which other features are available for defining options and handling the parsed results. On the CLI website there's also a link to some Usage Scenarios, but note that the samples contain a few bugs. The worst is the "Java Property Example" where hasArg() should be replaced with hasArgs().

    Use the Jakarta Commons mailing list to find out more information. There's no specific mailing list for CLI.

    CLI is an active project at Jakarta Commons. I've been told by John Keyes, part of the team developing CLI, that a beta of a new version, CLI2, is slated for availability in late April.

    In the download (see the Resources section at the end of the article) you'll find a class, TryCLI1, which may be used to write out the contents of an Options and a CommandLine instance. It's useful when experimenting with CLI. See the main method for documentation.

    How to Add Java Applets to Your Site

    New on the Java Boutique:

    New Review:

    Time Management Made Easy with the Quartz Enterprise Job Scheduler
    Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

    New Applet:

    Reverse Complement
    Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

    Elsewhere on internet.com:

    WebDeveloper Java
    Lots of Java information on webdeveloper.com

    WDVL Java
    Thorough Java resource at the Web Developer's Virtual Library.

    ScriptSearch Java
    Hundreds of free Java code files to download.

    jGuru: Your View of the Java Universe
    Customizable portal with online training, FAQs, regular news updates, and tutorials.