Contact at or 8097636691
Responsive Ads Here

Sunday, 1 July 2018

Apache Commons CLI - Argument Option

Apache Commons CLI - Argument Option

A Argument option is represented on a command line by its name and its corresponding value. For example, if option is present then user has to pass its value. Consider the following example, if we're printing logs to some file we want user to enter name of the log file with the argument option logFile.

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

public class CLITester {
   public static void main(String[] args) throws ParseException {

      Options options = new Options();

      Option logfile   = Option.builder()
         .argName("file" )
         .desc("use given file for log" )


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

      // has the logFile argument been passed?
      if(cmd.hasOption("logFile")) {
         //get the logFile argument passed
         System.out.println( cmd.getOptionValue( "logFile" ) );


Run the file while passing --logFile as option, name of the file as value of the option and see the result.
java CLITester --logFile test.log

No comments:

Post a Comment