-1

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
huma_23
  • 3
  • 2
  • 1
    There was a discussion on another thread: http://stackoverflow.com/questions/367706/is-there-a-good-command-line-argument-parser-for-java – Robert Navado Feb 04 '15 at 07:52

2 Answers2

0

you can check for parameters passed via the main method

So that if there is any and it is what you expect, You Print appropriate messages regarding the usage.

public static void main(String args[]){
    if(args.length > 0){
      //-----take appropraite action ----
      //----- if the value of the parameter is 'usage' --
      //-----print usage into e.t.c---
    }
    //---- other codes--
}
lightup
  • 634
  • 8
  • 18
0

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
    }
}
André Schild
  • 4,592
  • 5
  • 28
  • 42