This tutorial will guide you through how to do command line argument parsing easily. For this example we will use Commons-Cli package.
pom.xml
<properties> <commonscli.version>1.4</commonscli.version> </properties> <dependencies> <!-- https://mvnrepository.com/artifact/commons-cli/commons-cli --> <dependency> <groupId>commons-cli</groupId> <artifactId>commons-cli</artifactId> <version>${commonscli.version}</version> </dependency> </dependencies>
Imports
import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException;
Main
public static void main(String[] args) { final Options options = new Options(); Option startOption = new Option("s", "start", true, "Start the process."); startOption.setRequired(true); options.addOption(startOption); final HelpFormatter help = new HelpFormatter(); final CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (final ParseException e) { help.printHelp("java -jar myApp.jar", "My Header", options, "-s must be specified"); return; } final boolean doStart = Boolean.valueOf(cmd.getOptionValue("s")); if (doStart) { //Do my work here } }
You must be logged in to post a comment.