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
Release: 2024-12-19 19:24:16
Original
782 people have browsed it

How Can I Efficiently Parse Command-Line Arguments in Java?

How do I Parse Command Line Arguments in Java?

To efficiently parse command line arguments in Java, consider leveraging one of the following libraries:

  • Apache Commons CLI: http://commons.apache.org/cli/
  • JSAP (Java Simple Argument Parser): http://www.martiansoftware.com/jsap/

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);
    }
}
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template