Apache Commons CLI - Argument Option



Overview

An 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.

java CLITester --logFile test.log

Then the value of logFile option should be test.log passed as argument which we can use later to create a log file and store information.

Read the argument value using getOptionValue() method.

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

Example - Reading Arguments Based on Option passed

In this example, we're printing name of the log file passed with the argument option logFile.

CLITester.java

package com.tutorialspoint;

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()
         .longOpt("logFile")
         .argName("file" )
         .hasArg()
         .desc("use given file for log" )
         .get();

      options.addOption(logfile);
      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( "File name passed: " + cmd.getOptionValue( "logFile" ) );
      }
   }
}

Output

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
File name passed: test.log
Advertisements