Command line options with command-cli

How do you use command line arguments in Java?  The Java SDK does not come with library that can parse the arguments.  Parsing each argument is a tedious work, however.

The common-cli does the all the work for you.  The library can parse the input for short and long versions of the command line input.  The "-f" option should be the same with "--trefile", that is.  The options can be optional or mandatory.  If the required option is not there, it will print out the usage as specified.  Nice, is it?  It only is a matter of editing the pom.xml.  Here you go:

 
 <dependency>
    <groupId>commons-cli</groupId>
    <artifactId>commons-cli</artifactId>
    <version>1.4 </version>
 </dependency>


As for parsing the input arguments, set the Option and parse the command line with CommandLineParser with the option settings.  If any wrong option is set, the usage will be printed by HelpFormatter.

 
    import org.apache.commons.cli.CommandLine;
    import org.apache.commons.cli.CommandLineParser;
    import org.apache.commons.cli.DefaultParser;
    import org.apache.commons.cli.HelpFormatter;
    import org.apache.commons.cli.Options;

    public static void main(String args[]) {
        final String OPTION_FILE = "trefile";
        final String OPTION_USAGE= "usage";
        Options opt = new Options();
        opt.addOption("f", OPTION_FILE, true, "the TRE file");
        opt.addOption("?", OPTION_USAGE, false, "print this message");
        TreeEditor treeEditor = null;
        try {
            String treFile = "";

            CommandLineParser parser = new DefaultParser();
            CommandLine cmd = parser.parse(opt, args);

            if (cmd.hasOption(OPTION_FILE)) {
                treFile = cmd.getOptionValue(OPTION_FILE);
            }
            if (cmd.hasOption(OPTION_USAGE)) {
                throw new Exception();
            }
            
             // start your app with inFile

        } catch (Exception e) {
            HelpFormatter help=new HelpFormatter();
            help.printHelp("TreeEditor", opt);
            TreeEditor.log.error("Error starting TreeEditor", e);
        }
    }


TreeEditor is a Java project that uses the above mentioned command line argument parsing mechanisms.

Comments

Popular posts from this blog

Logging your Maven project with Logback

TreeEditor: Customizing Drag and Drop

Spring Tool Suite