You can do this easily just the same as you would for parsing normal program arguments. Here is a small example:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
System.out.println(Arrays.toString(args));
String host = args[1];
String user = args[3];
String password = args[5];
System.out.println("Host: " + host);
System.out.println("User: " + user);
System.out.println("Password: " + password);
}
}
If I run this program with the following command:
java Main --host hostname --user username --password password
This is the output:
[--host, hostname, --user, username, --password, password]
Host: hostname
User: username
Password: password
Alternatively, you can use a library like the Apache Commons CLI which includes a lot of utilities to parse command line arguments and options:
import org.apache.commons.cli.*;
public class Main {
public static void main(String[] args) {
Options options = new Options();
Option host = Option.builder()
.longOpt("host")
.hasArg()
.valueSeparator(' ')
.build();
Option user = Option.builder()
.longOpt("user")
.hasArg()
.valueSeparator(' ')
.build();
Option password = Option.builder()
.longOpt("password")
.hasArg()
.valueSeparator(' ')
.build();
options.addOption(host);
options.addOption(user);
options.addOption(password);
CommandLineParser parser = new DefaultParser();
try {
CommandLine line = parser.parse(options, args);
System.out.println("Host: " + line.getOptionValue("host"));
System.out.println("User: " + line.getOptionValue("user"));
System.out.println("Pass: " + line.getOptionValue("password"));
} catch (ParseException e) {
System.err.println("Parsing failed. Reason: " + e.getMessage());
}
}
}
However, this route requires you to add the Apache Commons CLI to your classpath and include it with your program (or add it as a dependency for a dependency management program like Maven or Gradle). It might seem like more work, but the Apache Commons CLI is very powerful and flexible and can make parsing a lot of command line options much less painful.
Here is the output of that sample class with the Apache Commons CLI:
Host: hostname
User: username
Password: password