Commons Cli 简明教程
Apache Commons CLI - Overview
Apache Commons CLI 是 Apache Commons 的组件,它源自 Java API,并提供一个 API 来解析传递给程序的命令行参数/选项。此 API 还支持输出与可用选项有关的帮助信息。
The Apache Commons CLI are the components of the Apache Commons which are derived from Java API and provides an API to parse command line arguments/options which are passed to the programs. This API also enables to print help related to options available.
命令行处理包含三个阶段。这些阶段在下面进行了说明 -
Command line processing comprises of three stages. These stages are explained below −
-
Definition Stage
-
Parsing Stage
-
Interrogation Stage
Definition Stage
在定义阶段,我们定义应用程序可以使用的选项,并根据实际情况操作。Commons CLI 提供 Options 类,该类是 Option 对象的容器。
In definition stage, we define the options that an application can take and act accordingly. Commons CLI provides Options class, which is a container for Option objects.
// create Options object
Options options = new Options();
// add a option
options.addOption("a", false, "add two numbers");
这里我们添加了一个选项标志 a,而第二个参数为 false,表明该选项不是必需的,而第三个参数表明该选项的描述。
Here we have added an option flag a, while false as second parameter, signifies that option is not mandatory and third parameter states the description of option.
Parsing Stage
在解析阶段,我们在创建解析器实例后解析使用命令行参数传递的选项。
In parsing stage, we parse the options passed using command line arguments after creating a parser instance.
//Create a parser
CommandLineParser parser = new DefaultParser();
//parse the options passed as command line arguments
CommandLine cmd = parser.parse( options, args);
Interrogation Stage
在查询阶段,我们检查是否存在特定选项,然后相应地处理该命令。
In Interrogation stage, we check if a particular option is present or not and then, process the command accordingly.
//hasOptions checks if option is present or not
if(cmd.hasOption("a")) {
// add the two numbers
} else if(cmd.hasOption("m")) {
// multiply the two numbers
}
Apache Commons CLI - Environment Setup
在本章中,我们将了解 Apache Commons CLI 的本地环境设置,以及如何在 Windows 2000/XP、Windows 95/98/ME 等中设置 Commons CLI 的路径。我们还将了解一些流行的 Java 编辑器以及如何下载 Commons CLI 存档。
In this chapter, we will learn about the local environment setup of Apache Commons CLI and how to set up the path of Commons CLI for Windows 2000/XP, Windows 95/98/ME etc. We will also understand about some popular java editors and how to download Commons CLI archive.
Local Environment Setup
如果您仍然愿意为 Java 编程语言设置环境,那么本章将指导您如何在机器上下载和设置 Java。请遵循以下步骤来设置环境。
If you are still willing to set up your environment for Java programming language, then this chapter will guide you on how to download and set up Java on your machine. Please follow the steps mentioned below to set up the environment.
Java SE 可从链接 https://www.oracle.com/java/technologies/oracle-java-archive-downloads.html 免费获得。因此,你可以根据自己的操作系统下载一个版本。
Java SE is freely available from the link https://www.oracle.com/java/technologies/oracle-java-archive-downloads.html. So you can download a version based on your operating system.
按照说明下载 Java 并运行 .exe 以在你的计算机上安装 Java。在你的计算机上安装 Java 后,你需要设置环境变量以指向正确的安装目录。
Follow the instructions to download Java and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set environment variables to point to correct installation directories.
Path for Windows 2000/XP
我们假设你已在 c:\Program Files\java\jdk 目录中安装了 Java。
We are assuming that you have installed Java in c:\Program Files\java\jdk directory.
-
Right-click on 'My Computer' and select 'Properties'.
-
Click on the 'Environment variables' button under the 'Advanced' tab.
-
Now, alter the 'Path' variable, so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your path to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'.
Path for Windows 95/98/ME
我们假设你已在 c:\Program Files\java\jdk 目录中安装了 Java。
We are assuming that you have installed Java in c:\Program Files\java\jdk directory.
-
Edit the 'C:\autoexec.bat' file and add the following line at the end − 'SET PATH=%PATH%;*C:\Program Files\java\jdk\bin'*.
Path for Linux, UNIX, Solaris, FreeBSD
应将环境变量 PATH 设置为已安装 Java 二进制文件的路径。如果您遇到问题,请参阅您的 shell 文档。
Environment variable PATH should be set to point, where the Java binaries have been installed. Refer to your shell documentation, if you have trouble doing this.
例如,如果您用 bash 作为您的 shell,则您将向您 '.bashrc: export PATH=/path/to/java:$PATH' 的末尾添加以下行
Example, if you use bash as your shell, then you would add the following line to the end of your '.bashrc: export PATH=/path/to/java:$PATH'
Popular Java Editors
要编写 Java 程序,您需要一个文本编辑器。市场中有许多高级集成开发环境可用。但目前,您可以考虑以下选项之一 −
To write your Java programs, you need a text editor. There are many sophisticated IDEs available in the market. But for now, you can consider one of the following −
-
Notepad − On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad.
-
Netbeans − It is a Java IDE that is open-source and free which can be downloaded from www.netbeans.org/index.html.
-
Eclipse − It is also a Java IDE developed by the eclipse open-source community and can be downloaded from www.eclipse.org.
Download Common CLI Archive
从 commons-cli-1.4-bin.zip 下载最新版本的 Apache Common CLI jar 文件。撰写本教程时,我们下载了 commons-cli-1.4-bin.zip 并将其复制到了 C:\Apache 文件夹。
Download the latest version of Apache Common CLI jar file from commons-cli-1.4-bin.zip. At the time of writing this tutorial, we have downloaded commons-cli-1.4-bin.zip and copied it into C:\>Apache folder.
OS |
Archive name |
Windows |
commons-cli-1.4-bin.zip |
Linux |
commons-cli-1.4-bin.tar.gz |
Mac |
commons-cli-1.4-bin.tar.gz |
Apache Common CLI Environment
设置 APACHE_HOME 环境变量,使其指向存储在您计算机上的 Apache jar 的基本目录位置。假设我们在不同操作系统上的 Apache 文件夹中以如下方式解压了 commonscollections4-4.1-bin.zip −
Set the APACHE_HOME environment variable to point to the base directory location where, Apache jar is stored on your machine. Assume that we have extracted commonscollections4-4.1-bin.zip in Apache folder on various Operating Systems as follows −
OS |
Output |
Windows |
Set the environment variable APACHE_HOME to C:\Apache |
Linux |
export APACHE_HOME = /usr/local/Apache |
Mac |
export APACHE_HOME = /Library/Apache |
CLASSPATH Variable
设置 CLASSPATH 环境变量,使其指向 Common CLI jar 位置。假设您已将 commons-cli-1.4.jar 存储在不同操作系统上的 Apache 文件夹中,如下所示 −
Set the CLASSPATH environment variable to point to the Common CLI jar location. Assume that you have stored commons-cli-1.4.jar in Apache folder on various Operating Systems as follows −
OS |
Output |
Windows |
Stores AIML bots</Set the environment variable CLASSPATH to %CLASSPATH%;%APACHE_HOME%\commons-cli-1.4.jar;.; |
Linux |
export CLASSPATH = $CLASSPATH:$APACHE_HOME/commons-cli-1.4.jar:. |
Mac |
export CLASSPATH = $CLASSPATH:$APACHE_HOME/commons-cli-1.4.jar:. |
Apache Commons CLI - First Application
让我们创建一个基于示例控制台的应用程序,其目的是根据所用的选项获取所传递数字的总和或乘积。
Let’s create a sample console based application, whose purpose is to get either sum of passed numbers or multiplication of passed numbers based on the options used.
创建一个名为 CLITester 的 java 类。
Create a java class named CLITester.
Example
CLITester.java
CLITester.java
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public class CLITester {
public static void main(String[] args) throws ParseException {
//***Definition Stage***
// create Options object
Options options = new Options();
// add option "-a"
options.addOption("a", false, "add numbers");
// add option "-m"
options.addOption("m", false, "multiply numbers");
//***Parsing Stage***
//Create a parser
CommandLineParser parser = new DefaultParser();
//parse the options passed as command line arguments
CommandLine cmd = parser.parse( options, args);
//***Interrogation Stage***
//hasOptions checks if option is present or not
if(cmd.hasOption("a")) {
System.out.println("Sum of the numbers: " + getSum(args));
} else if(cmd.hasOption("m")) {
System.out.println("Multiplication of the numbers: " + getMultiplication(args));
}
}
public static int getSum(String[] args) {
int sum = 0;
for(int i = 1; i < args.length ; i++) {
sum += Integer.parseInt(args[i]);
}
return sum;
}
public static int getMultiplication(String[] args) {
int multiplication = 1;
for(int i = 1; i < args.length ; i++) {
multiplication *= Integer.parseInt(args[i]);
}
return multiplication;
}
}
Output
运行文件,同时传递 -a 作为选项,并传递数字作为结果获取数字的总和。
Run the file, while passing -a as option and numbers to get the sum of the numbers as result.
java CLITester -a 1 2 3 4 5
Sum of the numbers: 15
运行文件,同时传递 -m 作为选项,并传递数字作为结果获取数字的乘积。
Run the file, while passing -m as option and numbers to get the multiplication of the numbers as result.
java CLITester -m 1 2 3 4 5
Multiplication of the numbers: 120
Apache Commons CLI - Option Properties
使用 Option 对象来表示传递到命令行程序的 Option。Option 对象具有以下各种属性。
Option object is used to represent the Option passed to command line program. Following are various properties that an Option object possess.
Sr.No |
Name (Type) &s; Description |
1 |
opt (String) Identification string of the Option. |
2 |
longOpt (String) Alias and more descriptive identification string. |
3 |
description (String) Description of the function of the option. |
4 |
required (boolean) Flag to check whether the option must appear on the command line. |
5 |
arg (boolean) Flag to check whether the option takes an argument. |
6 |
args (boolean) Flag to check whether the option takes more than one argument. |
7 |
optionalArg (boolean) Flag to check whether the option’s argument is optional. |
8 |
argName (String) Name of the argument value for the usage statement. |
9 |
valueSeparator (char) The character value used to split the argument string. |
10 |
type (Object) Argument type. |
11 |
value (String) Option value. |
12 |
values (String[]) Values of the option. |
Apache Commons CLI - Boolean Option
布尔选项在命令行中由其存在表示。例如,如果存在选项,那么其值为 true,否则,其会被视为 false。考虑以下示例,其中我们输出当前日期,如果存在 -t 标志。那么,我们还将输出时间。
A boolean option is represented on a command line by its presence. For example, if option is present, then its value is true, otherwise, it is considered as false. Consider the following example, where we are printing current date and if -t flag is present. Then, we will print time too.
Example
CLITester.java
CLITester.java
import java.util.Calendar;
import java.util.Date;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public class CLITester {
public static void main(String[] args) throws ParseException {
Options options = new Options();
options.addOption("t", false, "display time");
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse( options, args);
Calendar date = Calendar.getInstance();
int day = date.get(Calendar.DAY_OF_MONTH);
int month = date.get(Calendar.MONTH);
int year = date.get(Calendar.YEAR);
int hour = date.get(Calendar.HOUR);
int min = date.get(Calendar.MINUTE);
int sec = date.get(Calendar.SECOND);
System.out.print(day + "/" + month + "/" + year);
if(cmd.hasOption("t")) {
System.out.print(" " + hour + ":" + min + ":" + sec);
}
}
}
Apache Commons CLI - Argument Option
在命令行中,参数选项由其名称及其相应的值表示。例如,如果存在选项,那么用户必须传递其值。考虑以下示例,如果我们将日志输出到某个文件,为此,我们希望用户使用参数选项 logFile 输入日志文件的名称。
An Argument option is represented on a command line by its name and its corresponding value. For example, if option is present, then user has to pass its value. Consider the following example, if we are printing logs to some file, for which, we want user to enter name of the log file with the argument option logFile.
Example
CLITester.java
CLITester.java
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public class CLITester {
public static void main(String[] args) throws ParseException {
Options options = new Options();
Option logfile = Option.builder()
.longOpt("logFile")
.argName("file" )
.hasArg()
.desc("use given file for log" )
.build();
options.addOption(logfile);
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse( options, args);
// has the logFile argument been passed?
if(cmd.hasOption("logFile")) {
//get the logFile argument passed
System.out.println( cmd.getOptionValue( "logFile" ) );
}
}
}
Apache Commons CLI - Properties Option
Properties 选项在命令行上由其名称及其相应属性(如语法)表示,类似于 Java 属性文件。考虑以下示例,如果我们要传递以下选项 -DrollNo = 1 -Dclass = VI -Dname = Mahesh,我们应该将每个值作为属性进行处理。让我们看一看实现逻辑。
A Properties option is represented on a command line by its name and its corresponding properties like syntax, which is similar to java properties file. Consider the following example, if we are passing options like -DrollNo = 1 -Dclass = VI -Dname = Mahesh, we should process each value as properties. Let’s see the implementation logic in action.
Example
CLITester.java
CLITester.java
import java.util.Properties;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public class CLITester {
public static void main(String[] args) throws ParseException {
Options options = new Options();
Option propertyOption = Option.builder()
.longOpt("D")
.argName("property=value" )
.hasArgs()
.valueSeparator()
.numberOfArgs(2)
.desc("use value for given properties" )
.build();
options.addOption(propertyOption);
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse( options, args);
if(cmd.hasOption("D")) {
Properties properties = cmd.getOptionProperties("D");
System.out.println("Class: " + properties.getProperty("class"));
System.out.println("Roll No: " + properties.getProperty("rollNo"));
System.out.println("Name: " + properties.getProperty("name"));
}
}
}
Apache Commons CLI - Posix Parser
Posix 解析器用于解析类似于 Posix 的传递的参数。它现在已被弃用,并已被 DefaultParser 替换。
A Posix parser is use to parse Posix like arguments passed. It is now deprecated and is replaced by DefaultParser.
Example
CLITester.java
CLITester.java
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
public class CLITester {
public static void main(String[] args) throws ParseException {
//Create posix like options
Options posixOptions = new Options();
posixOptions.addOption("D", false, "Display");
posixOptions.addOption("A", false, "Act");
CommandLineParser posixParser = new PosixParser();
CommandLine cmd = posixParser.parse(posixOptions, args);
if( cmd.hasOption("D") ) {
System.out.println("D option was used.");
}
if( cmd.hasOption("A") ) {
System.out.println("A option was used.");
}
}
}
Apache Commons CLI - GNU Parser
GNU 解析器用于解析类似 gnu 的传递参数。现在它已被弃用,并替换为 DefaultParser。
A GNU parser is use to parse gnu like arguments passed. It is now deprecated and is replaced by DefaultParser.
Example
CLITester.java
CLITester.java
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public class CLITester {
public static void main(String[] args) throws ParseException {
//Create GNU like options
Options gnuOptions = new Options();
gnuOptions.addOption("p", "print", false, "Print")
.addOption("g", "gui", false, "GUI")
.addOption("n", true, "Scale");
CommandLineParser gnuParser = new GnuParser();
CommandLine cmd = gnuParser.parse(gnuOptions, args);
if( cmd.hasOption("p") ) {
System.out.println("p option was used.");
}
if( cmd.hasOption("g") ) {
System.out.println("g option was used.");
}
if( cmd.hasOption("n") ) {
System.out.println("Value passed: " + cmd.getOptionValue("n"));
}
}
}
Apache Commons CLI - Usage Example
Apache Commons CLI 提供 HelpFormatter 类以输出命令行参数的使用指南。请参阅下面给出的示例 -
Apache Commons CLI provides HelpFormatter class to print the usage guide of command line arguments. See the example given below −
Example
CLITester.java
CLITester.java
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public class CLITester {
public static void main(String[] args) throws ParseException {
Options options = new Options();
options.addOption("p", "print", false, "Send print request to printer.")
.addOption("g", "gui", false, "Show GUI Application")
.addOption("n", true, "No. of copies to print");
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("CLITester", options);
}
}
Apache Commons CLI - Help Example
Apache Commons CLI 提供 HelpFormatter 类来打印与命令行参数相关的帮助。参见示例。
Apache Commons CLI provides HelpFormatter class to print the help related to command line arguments. See the example.
Example
CLITester.java
CLITester.java
import java.io.PrintWriter;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public class CLITester {
public static void main(String[] args) throws ParseException {
Options options = new Options();
options.addOption("p", "print", false, "Send print request to printer.")
.addOption("g", "gui", false, "Show GUI Application")
.addOption("n", true, "No. of copies to print");
HelpFormatter formatter = new HelpFormatter();
final PrintWriter writer = new PrintWriter(System.out);
formatter.printUsage(writer,80,"CLITester", options);
writer.flush();
}
}