Over a million developers have joined DZone.

Parsing Simple Command Line Arguments In Java, Using The The Commons CLI Library.

// Skeleton to read in two command line arguments, one mandatory, one optional

package snippets;

import org.apache.commons.cli.*;

 * Stub program that reads command line arguments
public class CommandLineProgram {

	private static Options options = null; // Command line options
	private static final String PROPERTIES_LOCATION_OPTION = "f";
	private static final String OUTPUT_FILE_OPTION = "o";
	private static final String DEFAULT_OUTPUT_FILE = "out.feed";
	private CommandLine cmd = null; // Command Line arguments
	private String outputFile = DEFAULT_OUTPUT_FILE;
		options = new Options();
		options.addOption(PROPERTIES_LOCATION_OPTION, true, 
				"Data file location");
		options.addOption(OUTPUT_FILE_OPTION, false, "Output file. " + DEFAULT_OUTPUT_FILE + " by default ");
	 * @param args
	public static void main(String[] args) {
		CommandLineProgram cliProg = new CommandLineProgram();
	 * Validate and set command line arguments.
	 * Exit after printing usage if anything is astray
	 * @param args String[] args as featured in public static void main()
	private void loadArgs(String[] args){
		CommandLineParser parser = new PosixParser();
		try {
			cmd = parser.parse(options, args);
		} catch (ParseException e) {
			System.err.println("Error parsing arguments");
		// Check for mandatory args
		if (! cmd.hasOption(PROPERTIES_LOCATION_OPTION)){
			HelpFormatter formatter = new HelpFormatter();
			formatter.printHelp("java -jar this_jar.jar", options);
		// Look for optional args.
		if (cmd.hasOption(OUTPUT_FILE_OPTION)){
			outputFile = cmd.getOptionValue(OUTPUT_FILE_OPTION);


The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}