How do I parse command line arguments in Java?

What is a good way of parsing command line arguments in Java?


Solution 1:

Check these out:

  • http://commons.apache.org/cli/
  • http://www.martiansoftware.com/jsap/

Or roll your own:

  • http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

For instance, this is how you use commons-cli to parse 2 string arguments:

import org.apache.commons.cli.*;

public class Main {


    public static void main(String[] args) throws Exception {

        Options options = new Options();

        Option input = new Option("i", "input", true, "input file path");
        input.setRequired(true);
        options.addOption(input);

        Option output = new Option("o", "output", true, "output file");
        output.setRequired(true);
        options.addOption(output);

        CommandLineParser parser = new DefaultParser();
        HelpFormatter formatter = new HelpFormatter();
        CommandLine cmd = null;//not a good practice, it serves it purpose 

        try {
            cmd = parser.parse(options, args);
        } catch (ParseException e) {
            System.out.println(e.getMessage());
            formatter.printHelp("utility-name", options);

            System.exit(1);
        }

        String inputFilePath = cmd.getOptionValue("input");
        String outputFilePath = cmd.getOptionValue("output");

        System.out.println(inputFilePath);
        System.out.println(outputFilePath);

    }

}

usage from command line:

$> java -jar target/my-utility.jar -i asd                                                                                       
Missing required option: o

usage: utility-name
 -i,--input <arg>    input file path
 -o,--output <arg>   output file

Solution 2:

Take a look at the more recent JCommander.

I created it. I’m happy to receive questions or feature requests.

Solution 3:

I have been trying to maintain a list of Java CLI parsers.

  • Airline
    • Active Fork: https://github.com/rvesse/airline
  • argparse4j
  • argparser
  • args4j
  • clajr
  • cli-parser
  • CmdLn
  • Commandline
  • DocOpt.java
  • dolphin getopt
  • DPML CLI (Jakarta Commons CLI2 fork)
  • Dr. Matthias Laux
  • Jakarta Commons CLI
  • jargo
  • jargp
  • jargs
  • java-getopt
  • jbock
  • JCLAP
  • jcmdline
  • jcommander
  • jcommando
  • jewelcli (written by me)
  • JOpt simple
  • jsap
  • naturalcli
  • Object Mentor CLI article (more about refactoring and TDD)
  • parse-cmd
  • ritopt
  • Rop
  • TE-Code Command
  • picocli has ANSI colorized usage help and autocomplete

Solution 4:

It is 2021, time to do better than Commons CLI... :-)

Should you build your own Java command line parser, or use a library?

Many small utility-like applications probably roll their own command line parsing to avoid the additional external dependency. picocli may be an interesting alternative.

Picocli is a modern library and framework for building powerful, user-friendly, GraalVM-enabled command line apps with ease. It lives in 1 source file so apps can include it as source to avoid adding a dependency.

It supports colors, autocompletion, subcommands, and more. Written in Java, usable from Groovy, Kotlin, Scala, etc.

Minimal usage help with ANSI colors

Features:

  • Annotation based: declarative, avoids duplication and expresses programmer intent
  • Convenient: parse user input and run your business logic with one line of code
  • Strongly typed everything - command line options as well as positional parameters
  • POSIX clustered short options (<command> -xvfInputFile as well as <command> -x -v -f InputFile)
  • Fine-grained control: an arity model that allows a minimum, maximum and variable number of parameters, e.g, "1..*", "3..5"
  • Subcommands (can be nested to arbitrary depth)
  • Feature-rich: composable arg groups, splitting quoted args, repeatable subcommands, and many more
  • User-friendly: usage help message uses colors to contrast important elements like option names from the rest of the usage help to reduce the cognitive load on the user
  • Distribute your app as a GraalVM native image
  • Works with Java 5 and higher
  • Extensive and meticulous documentation

The usage help message is easy to customize with annotations (without programming). For example:

Extended usage help message (source)

I couldn't resist adding one more screenshot to show what usage help messages are possible. Usage help is the face of your application, so be creative and have fun!

picocli demo

Disclaimer: I created picocli. Feedback or questions very welcome.