Explain Codes LogoExplain Codes Logo

How do I parse command line arguments in Java?

java
command-line-arguments
parser-engineering
best-practices
Alex KataevbyAlex Kataev·Sep 23, 2024
TLDR

Here's how you can quickly parse command line arguments in Java using args4j:

import org.kohsuke.args4j.*; public class CommandLineApp { @Option(name="-n", usage="Sets the user name") private String name; // Guess what? We keep your name here public static void main(String[] args) { CommandLineApp app = new CommandLineApp(); CmdLineParser parser = new CmdLineParser(app); try { parser.parseArgument(args); // Got some incomprehensible magics around here System.out.println("Hello, " + app.name); // Who doesn't like greetings? } catch (CmdLineException e) { System.err.println(e.getMessage()); parser.printUsage(System.err); // Cause handling exceptions is a cool thing } } }

Run your app with -n YourName to experience the magic. The args4j library leverages the effective power of annotations for argument definitions, making your life a bit easier on planet Java.

Sophisticated parsing: Apache Commons CLI

When a project demands more dynamic parsing capabilities, Apache Commons CLI becomes your best friend. The code below outlines its usage:

import org.apache.commons.cli.*; public class App { public static void main(String[] args) { Options options = new Options(); options.addOption("n", true, "Sets the user name"); // More options than a Sunday brunch menu CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); // Formatter. Not the one in your mobile settings try { CommandLine cmd = parser.parse(options, args); if(cmd.hasOption("n")) { System.out.println("Hello, " + cmd.getOptionValue("n")); // Sweet personalization here } } catch (ParseException e) { System.out.println(e.getMessage()); formatter.printHelp("utility-name", options); // Who said you can't ask for help? } } }

When you require thorough documentation and a structured approach, Apache Commons CLI is worth considering.

Advanced feats using Picocli

To unlock advanced features like colors, autocompletion, and subcommands, consider using Picocli:

import picocli.CommandLine; import picocli.CommandLine.Option; @CommandLine.Command(name = "greet", mixinStandardHelpOptions = true) // Meet the Command boss public class GreetCommand implements Runnable { @Option(names = {"-n", "--name"}, description = "The name of the person to greet") // Cause options are fancy String name; public void run() { System.out.printf("Hello, %s!%n", name); // And here we roll out the red carpet } public static void main(String[] args) { int exitCode = new CommandLine(new GreetCommand()).execute(args); // Execute. Thanos loves it. You'll love it too. System.exit(exitCode); } }

Picocli is a versatile library best suited for building complex CLI applications with native image support using GraalVM.

Custom parser route: Java's Scanner

When you want to go off-track or learn by doing, Java's Scanner class comes into play:

import java.util.Scanner; public class CustomParser { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter your name: "); // It's a conversation, minus the awkward silence String name = scanner.nextLine(); // The grand reveal System.out.println("Hello, " + name); // The crowd goes wild } }

The Scanner provides an opportunity to implement custom parsing logic, allowing you to gain full control over parsing while aligning the flow as per best practices.

Library selection guide

When selecting a library, evaluate specific features:

  • Apache Commons CLI: Traditional command line applications.
  • Picocli: Applications requiring advanced features, Java 5 and above.
  • JCommander, args4j: Clean API, ease of use, and maintenance.
  • Airline, argparse4j: Unique features suited for specific needs.