Skip to content

Instantly share code, notes, and snippets.

@sarnobat
Last active September 19, 2017 21:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sarnobat/44a88fb741a4bbc30bf1dc852af36b37 to your computer and use it in GitHub Desktop.
Save sarnobat/44a88fb741a4bbc30bf1dc852af36b37 to your computer and use it in GitHub Desktop.
java command line options
import org.apache.commons.cli.*;
/** TODO: which maven artifact version do we need? */
public class CommandLineOptionsExample {
public static void main(String[] args) {
String port;
_parseOptions: {
Options options = new Options()
.addOption("h", "help", false, "show help.");
Option option = Option.builder("a").longOpt("block-size").desc("use SIZE-byte blocks").hasArg().argName("SIZE")
.build();
options.addOption(option);
// This doesn't work with java 7
// "hasarg" is needed when the option takes a value
options.addOption(Option.builder("p").longOpt("port").hasArg().required().build());
try {
CommandLine cmd = new DefaultParser().parse(options, args);
port = cmd.getOptionValue("p", "4444");
System.out.println("CommandLineOptionsExample.parse() - SRIDHAR: port = " + port);
System.out.println("CommandLineOptionsExample.parse() - SRIDHAR: a = " + cmd.getOptionValue("a"));
if (cmd.hasOption("h")) {
// This prints out some help
HelpFormatter formater = new HelpFormatter();
formater.printHelp("Main", options);
System.exit(0);
}
} catch (ParseException e) {
e.printStackTrace();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment