Last active
September 19, 2017 21:37
-
-
Save sarnobat/44a88fb741a4bbc30bf1dc852af36b37 to your computer and use it in GitHub Desktop.
java command line options
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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