What is a good way of parsing command line arguments in Java?
To parse command line parameters, Commons CLI uses the DefaultParser implementation of the CommandlineParser interface. DefaultParser has a method called parse() which accepts the options object and the args from the command line. Finally, you can use the HelpFormatter to print the help information to the user.
public class CommandLineParser extends java.lang.Object. This class is for parsing command lines, as typed by a user to a Java program. The CommandLineParser organizes the command line into a series of settings and values for easier querying by the actual program.
# construct the argument parser and parse the arguments ap = argparse. ArgumentParser() ap. add_argument("-d", "--dataset", required=True, help="Path to the directory of indexed images") ap. add_argument("-f", "--features-db", required=True, help="Path to the features database") ap.
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: o usage: 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With