Page cover

βœ‚οΈCommand Argument Parser

Define and parse command line arguments

KCmdArgParser Class Overview

  • Define allowed options and arguments

  • Parsing of the command line arguments

  • Methods to query and retrieve options and arguments

Example

import ch.k43.util.KCmdArgParser;

public class CmdParser {
	
   public static void main(String[] args) {

      // Parser syntax: -a and -l optional, one parameter required
      final String ARG_SYNTAX = "?-l:?-a:!.";			
		
      // Initialize command line parser with argument syntax
      KCmdArgParser argParser = new KCmdArgParser(ARG_SYNTAX);
		
      // Parse command line arguments
      if (!argParser.parse(args)) {
         System.out.println("Syntax error: " + argParser.getLastError());
         System.exit(1);
      }
		
      System.out.println("Option -l: " + argParser.hasOption("-l"));
      System.out.println("Option -a: " + argParser.hasOption("-a"));
      System.out.println("Parameter: " + argParser.getArgument());
   }
}

Output

% CmdParser -l file.txt
Option -l: true
Option -a: false
Parameter: file.txt

% CmdParser -x file.txt
Syntax error: Command line option not supported: -x

Last updated