Search code examples
javacommand-line-interfaceutility

How to implement utility feature in a command line tool


I have developed a commandline tool by name translator in java and I run this tool by creating a jar file and using below command

java -jar translator.jar < input1 > 

now I have been asked to add a usage/ utility feature to this tool, like example how when we type java on command line it shows

usage:java [-options] class [args..]

...... etc I want to implement a similar feature for my tool . I am not understanding from where to begin as this is the first time I am working on building a command line tool.


Solution

  • If you don't want to handle the arguments yourself, you can use the CLI library from the apache commons project.

    For very small projects this usually doesn't make sense, but when you have more and more options, then it is a simple thing to use.

    The code flow is then like this example:

    public static void main(String args[]){
        // create Options object
        Options options = new Options();
    
        // add t option
        options.addOption("t", false, "display current time");
    
        CommandLineParser parser = new DefaultParser();
        CommandLine cmd = parser.parse( options, args);
    
        if(cmd.hasOption("t")) {
            // print the date and time
        }
        else {
            // print the date
        }
    }