import org.apache.commons.cli.Option;
public class CommandLineParameters {
public static final Option VERBOSE_OPTION = Option.builder("v")
.longOpt("verbose")
.desc("Enable verbose output")
.build();
public static final Option INPUT_OPTION = Option.builder("i")
.longOpt("input")
.desc("Input file")
.hasArg()
.argName("file")
.required()
.build();
}
import org.apache.commons.cli.*;
public class CommandLineParser {
public static void main(String[] args) {
Options options = new Options();
options.addOption(CommandLineParameters.VERBOSE_OPTION);
options.addOption(CommandLineParameters.INPUT_OPTION);
// Create command line parser
CommandLineParser parser = new DefaultParser();
try {
// Analyze the command line parameters
CommandLine commandLine = parser.parse(options, args);
// Treatment the results of the analysis
if (commandLine.hasOption(CommandLineParameters.VERBOSE_OPTION.getOpt())) {
// If the Verbose option is enabled
System.out.println("Verbose output enabled");
}
if (commandLine.hasOption(CommandLineParameters.INPUT_OPTION.getOpt())) {
// Get the input file path
String inputFile = commandLine.getOptionValue(CommandLineParameters.INPUT_OPTION.getOpt());
System.out.println("Input file: " + inputFile);
}
} catch (ParseException e) {
// Treatment analysis abnormalities
System.err.println("Failed to parse command line arguments: " + e.getMessage());
}
}
}
In the above sample code, we resolve the command line parameters by calling the method of `CommandLineParser.parse ()` and process the analysis results through the `Commandline` object.We used the `haSOption ()` method to check whether the Verbose option enabled and using the `GetOptionValue ()" method to get the input file path.
3. Compilation and running program: After completing the custom command line processor class, we can use the Java compiler to compile it into an executable bytecode file and execute in the command line.
Here are examples of compilation and running programs:
javac CommandLineParser.java
java CommandLineParser -v -i input.txt
In the above example command, we passed the two parameters of `-v` and` `-i input.txt` to enable the Verbose option and specify the input file.
Summarize:
By customizing command line processors, we can handle the command line parameters in Java.By defining the steps of parameters, creating command line parsers, and processing the resolution results, we can flexibly control the behavior of the program and provide a variety of options to meet different needs.
I hope this article will help you understand how to customize command line processors in the Java class library!