Parsing command line arguments is a common task when working with Java applications. Various approaches exist to accomplish this effectively.
If you prefer to avoid external libraries, you can roll your own command line argument parser using Java's built-in classes. The java.util.Scanner class allows you to read input from the command line and parse it into the appropriate data types.
import org.apache.commons.cli.*; public class Main { public static void main(String[] args) throws Exception { // Define command line options 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); // Parse command line arguments CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; // Bad practice, only for demonstration purposes try { cmd = parser.parse(options, args); } catch (ParseException e) { System.out.println(e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("utility-name", options); System.exit(1); } // Retrieve parsed values String inputFilePath = cmd.getOptionValue("input"); String outputFilePath = cmd.getOptionValue("output"); // Use the parsed arguments System.out.println(inputFilePath); System.out.println(outputFilePath); } }
Usage:
$ 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 to Effectively Parse Command Line Arguments in Java?. For more information, please follow other related articles on the PHP Chinese website!