Home >Java >javaTutorial >How Can I Efficiently Parse Command Line Arguments in Java?

How Can I Efficiently Parse Command Line Arguments in Java?

Susan Sarandon
Susan SarandonOriginal
2024-12-30 13:12:10472browse

How Can I Efficiently Parse Command Line Arguments in Java?

Parsing Command Line Arguments in Java

When dealing with command line arguments, parsing them efficiently and effectively is crucial for developing robust Java applications. Various approaches are available to achieve this:

Third-Party Libraries:

  • Apache Commons CLI: A comprehensive library for parsing command lines, handling flags, and validating arguments.
  • JSAP (Java Simple Argument Parser): A user-friendly and powerful library for parsing complex command lines.

DIY Parsing:

  • java.util.Scanner: While not specifically designed for parsing command line arguments, Scanner can be utilized for this purpose.

Example Usage:

Consider parsing two string arguments using Apache Commons CLI:

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;

        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);
    }
}

Command line 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 Can I Efficiently Parse Command Line Arguments in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn