How do I Parse Command Line Arguments in Java?
To efficiently parse command line arguments in Java, consider leveraging one of the following libraries:
Java also provides the Scanner class for manual argument parsing: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Example using Commons CLI:
To parse two string arguments using Commons CLI, create a CommandLineParser and parse the arguments using .parse(...).
import org.apache.commons.cli.*; public class Main { public static void main(String[] args) throws Exception { // Create options Options options = new Options(); options.addOption("i", "input", true, "input file path"); options.getOption("i").setRequired(true); options.addOption("o", "output", true, "output file"); options.getOption("o").setRequired(true); // Parse arguments CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); // Get parsed values 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
The above is the detailed content of How Can I Efficiently Parse Command-Line Arguments in Java?. For more information, please follow other related articles on the PHP Chinese website!