How do I parse command line arguments in Java?
Check these out:
Or roll your own:
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: ousage: utility-name -i,--input <arg> input file path -o,--output <arg> output file
Take a look at the more recent JCommander.
I created it. I’m happy to receive questions or feature requests.
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