Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing arguments to a Java command line program

What if I wanted to parse this:

java MyProgram -r opt1 -S opt2 arg1 arg2 arg3 arg4 --test -A opt3 

And the result I want in my program is:

regular Java args[]  of size=4 org.apache.commons.cli.Options[]  of size=3 org.apache.commons.cli.Options[] #2 of size=1 

I would prefer to use Apache Commons CLI, but the documentation is a little unclear about the case I present above. Specifically, the documentation doesn't tell you how to handle options of the 3rd type I specify below:

1. options with a "-" char 2. options with a "--" char 3. options without any marker, or "bare args" 

I wish that Apache Commons CLI would work but STILL be able to pass regular args to the program if those args didn't have a option prefix. Maybe it does but the documentation doesnt say so as I read through it...

like image 714
djangofan Avatar asked Sep 07 '11 23:09

djangofan


People also ask

How do you parse a command line argument in Java?

To parse command line parameters, Commons CLI uses the DefaultParser implementation of the CommandlineParser interface. DefaultParser has a method called parse() which accepts the options object and the args from the command line. Finally, you can use the HelpFormatter to print the help information to the user.

How do I pass a command line argument to a program?

If you want to pass command line arguments then you will have to define the main() function with two arguments. The first argument defines the number of command line arguments and the second argument is the list of command line arguments.

What is command line parser Java?

public class CommandLineParser extends java.lang.Object. This class is for parsing command lines, as typed by a user to a Java program. The CommandLineParser organizes the command line into a series of settings and values for easier querying by the actual program.


2 Answers

Use the Apache Commons CLI library commandline.getArgs() to get arg1, arg2, arg3, and arg4. Here is some code:

      import org.apache.commons.cli.CommandLine;     import org.apache.commons.cli.Option;     import org.apache.commons.cli.Options;     import org.apache.commons.cli.Option.Builder;     import org.apache.commons.cli.CommandLineParser;     import org.apache.commons.cli.DefaultParser;     import org.apache.commons.cli.ParseException;      public static void main(String[] parameters)     {         CommandLine commandLine;         Option option_A = Option.builder("A")             .required(true)             .desc("The A option")             .longOpt("opt3")             .build();         Option option_r = Option.builder("r")             .required(true)             .desc("The r option")             .longOpt("opt1")             .build();         Option option_S = Option.builder("S")             .required(true)             .desc("The S option")             .longOpt("opt2")             .build();         Option option_test = Option.builder()             .required(true)             .desc("The test option")             .longOpt("test")             .build();         Options options = new Options();         CommandLineParser parser = new DefaultParser();          String[] testArgs =         { "-r", "opt1", "-S", "opt2", "arg1", "arg2",           "arg3", "arg4", "--test", "-A", "opt3", };          options.addOption(option_A);         options.addOption(option_r);         options.addOption(option_S);         options.addOption(option_test);          try         {             commandLine = parser.parse(options, testArgs);              if (commandLine.hasOption("A"))             {                 System.out.print("Option A is present.  The value is: ");                 System.out.println(commandLine.getOptionValue("A"));             }              if (commandLine.hasOption("r"))             {                 System.out.print("Option r is present.  The value is: ");                 System.out.println(commandLine.getOptionValue("r"));             }              if (commandLine.hasOption("S"))             {                 System.out.print("Option S is present.  The value is: ");                 System.out.println(commandLine.getOptionValue("S"));             }              if (commandLine.hasOption("test"))             {                 System.out.println("Option test is present.  This is a flag option.");             }              {                 String[] remainder = commandLine.getArgs();                 System.out.print("Remaining arguments: ");                 for (String argument : remainder)                 {                     System.out.print(argument);                     System.out.print(" ");                 }                  System.out.println();             }          }         catch (ParseException exception)         {             System.out.print("Parse error: ");             System.out.println(exception.getMessage());         }     }  
like image 143
DwB Avatar answered Oct 06 '22 08:10

DwB


You could just do it manually.

NB: might be better to use a HashMap instead of an inner class for the opts.

/** convenient "-flag opt" combination */ private class Option {      String flag, opt;      public Option(String flag, String opt) { this.flag = flag; this.opt = opt; } }  static public void main(String[] args) {     List<String> argsList = new ArrayList<String>();       List<Option> optsList = new ArrayList<Option>();     List<String> doubleOptsList = new ArrayList<String>();      for (int i = 0; i < args.length; i++) {         switch (args[i].charAt(0)) {         case '-':             if (args[i].length < 2)                 throw new IllegalArgumentException("Not a valid argument: "+args[i]);             if (args[i].charAt(1) == '-') {                 if (args[i].length < 3)                     throw new IllegalArgumentException("Not a valid argument: "+args[i]);                 // --opt                 doubleOptsList.add(args[i].substring(2, args[i].length));             } else {                 if (args.length-1 == i)                     throw new IllegalArgumentException("Expected arg after: "+args[i]);                 // -opt                 optsList.add(new Option(args[i], args[i+1]));                 i++;             }             break;         default:             // arg             argsList.add(args[i]);             break;         }     }     // etc } 
like image 38
Charles Goodwin Avatar answered Oct 06 '22 08:10

Charles Goodwin