Apache Commons CLI - 快速指南
Apache Commons CLI - 概述
Apache Commons CLI 是 Apache Commons 的元件,它源自 Java API,並提供了一個 API 來解析傳遞給程式的命令列引數/選項。此 API 還能夠列印與可用選項相關的幫助資訊。
命令列處理包含三個階段。這些階段解釋如下:
- 定義階段
- 解析階段
- 詢問階段
定義階段
在定義階段,我們定義應用程式可以接受的選項並相應地採取行動。Commons CLI 提供 Options 類,它是一個 Option 物件的容器。
// create Options object
Options options = new Options();
// add a option
options.addOption("a", false, "add two numbers");
在這裡,我們添加了一個選項標誌 a,第二個引數為 false,表示該選項不是必需的,第三個引數說明了該選項的描述。
解析階段
在解析階段,我們在建立解析器例項後,解析使用命令列引數傳遞的選項。
//Create a parser CommandLineParser parser = new DefaultParser(); //parse the options passed as command line arguments CommandLine cmd = parser.parse( options, args);
詢問階段
在詢問階段,我們檢查特定選項是否存在,然後相應地處理命令。
//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 - 環境設定
在本章中,我們將學習 Apache Commons CLI 的本地環境設定,以及如何為 Windows 2000/XP、Windows 95/98/ME 等設定 Commons CLI 的路徑。我們還將瞭解一些流行的 Java 編輯器以及如何下載 Commons CLI 歸檔檔案。
本地環境設定
如果您仍然希望為 Java 程式語言設定環境,那麼本章將指導您如何在您的機器上下載和設定 Java。請按照下面提到的步驟設定環境。
可以從以下連結免費獲得 Java SE:https://www.oracle.com/java/technologies/oracle-java-archive-downloads.html。因此,您可以根據您的作業系統下載一個版本。
按照說明下載 Java 並執行 .exe 檔案以在您的機器上安裝 Java。在您的機器上安裝 Java 後,您需要設定環境變數以指向正確的安裝目錄。
Windows 2000/XP 路徑
我們假設您已將 Java 安裝在 **c:\Program Files\java\jdk** 目錄中。
右鍵單擊 **“我的電腦”** 並選擇 **“屬性”**。
在 **“高階”** 選項卡下單擊 **“環境變數”** 按鈕。
現在,修改 **“Path”** 變數,使其也包含 Java 可執行檔案的路徑。例如,如果路徑當前設定為 **'C:\WINDOWS\SYSTEM32'**,則將您的路徑更改為 **'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'**。
Windows 95/98/ME 路徑
我們假設您已將 Java 安裝在 **c:\Program Files\java\jdk** 目錄中。
編輯 **'C:\autoexec.bat'** 檔案,並在末尾新增以下行:**'SET PATH=%PATH%;C:\Program Files\java\jdk\bin'**。
Linux、UNIX、Solaris、FreeBSD 路徑
應將環境變數 PATH 設定為指向已安裝 Java 二進位制檔案的目錄。如果您遇到問題,請參考您的 shell 文件。
例如,如果您使用 bash 作為 shell,則您會在 '.bashrc' 檔案末尾新增以下行:'export PATH=/path/to/java:$PATH'
流行的 Java 編輯器
要編寫 Java 程式,您需要一個文字編輯器。市場上有很多複雜的 IDE。但就目前而言,您可以考慮以下其中一種:
**記事本** - 在 Windows 機器上,您可以使用任何簡單的文字編輯器,如記事本(本教程推薦使用)、TextPad。
**Netbeans** - 這是一個開源且免費的 Java IDE,可以從 www.netbeans.org/index.html 下載。
**Eclipse** - 它也是一個由 Eclipse 開源社群開發的 Java IDE,可以從 www.eclipse.org 下載。
下載 Common CLI 歸檔檔案
從 commons-cli-1.4-bin.zip 下載 Apache Common CLI jar 檔案的最新版本。在撰寫本教程時,我們下載了 commons-cli-1.4-bin.zip 並將其複製到 C:\>Apache 資料夾中。
| 作業系統 | 歸檔檔名 |
|---|---|
| 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 環境
設定 **APACHE_HOME** 環境變數以指向 Apache jar 檔案儲存在您機器上的基本目錄位置。假設我們在各種作業系統上的 Apache 資料夾中解壓了 commonscollections4-4.1-bin.zip,如下所示:
| 作業系統 | 輸出 |
|---|---|
| Windows | 將環境變數 APACHE_HOME 設定為 C:\Apache |
| Linux | export APACHE_HOME = /usr/local/Apache |
| Mac | export APACHE_HOME = /Library/Apache |
CLASSPATH 變數
設定 **CLASSPATH** 環境變數以指向 Common CLI jar 檔案的位置。假設您已將 commons-cli-1.4.jar 儲存在各種作業系統上的 Apache 資料夾中,如下所示:
| 作業系統 | 輸出 |
|---|---|
| Windows | 儲存 AIML 機器人 <設定環境變數 CLASSPATH 為 %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 - 第一個應用程式
讓我們建立一個基於控制檯的示例應用程式,其目的是根據使用的選項獲取傳遞數字的總和或乘積。
建立一個名為 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;
}
}
輸出
執行該檔案,同時傳遞 -a 作為選項和數字以獲取數字的總和作為結果。
java CLITester -a 1 2 3 4 5 Sum of the numbers: 15
執行該檔案,同時傳遞 -m 作為選項和數字以獲取數字的乘積作為結果。
java CLITester -m 1 2 3 4 5 Multiplication of the numbers: 120
Apache Commons CLI - 選項屬性
Option 物件用於表示傳遞給命令列程式的 Option。以下是 Option 物件擁有的各種屬性。
| 序號 | 名稱 (型別) &s; 描述 |
|---|---|
| 1 |
opt (String) Option 的標識字串。 |
| 2 |
longOpt (String) 別名和更具描述性的標識字串。 |
| 3 |
description (String) 選項功能的描述。 |
| 4 |
required (boolean) 用於檢查選項是否必須出現在命令列中的標誌。 |
| 5 |
arg (boolean) 用於檢查選項是否需要引數的標誌。 |
| 6 |
args (boolean) 用於檢查選項是否需要多個引數的標誌。 |
| 7 |
optionalArg (boolean) 用於檢查選項的引數是否可選的標誌。 |
| 8 |
argName (String) 用法語句的引數值的名稱。 |
| 9 |
valueSeparator (char) 用於分割引數字串的字元值。 |
| 10 |
type (Object) 引數型別。 |
| 11 |
value (String) 選項值。 |
| 12 |
values (String[]) 選項的值。 |
Apache Commons CLI - 布林型選項
布林型選項由其存在於命令列中來表示。例如,如果選項存在,則其值為 true,否則,則被視為 false。考慮以下示例,我們正在列印當前日期,如果存在 -t 標誌,那麼我們也將列印時間。
示例
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);
}
}
}
輸出
執行該檔案而不傳遞任何選項並檢視結果。
java CLITester 12/11/2017
執行該檔案,同時傳遞 -t 作為選項並檢視結果。
java CLITester 12/11/2017 4:13:10
Apache Commons CLI - 引數選項
引數選項由其名稱及其對應值在命令列中表示。例如,如果選項存在,則使用者必須傳遞其值。考慮以下示例,如果我們將日誌列印到某個檔案中,為此,我們希望使用者使用引數選項 logFile 輸入日誌檔案的名稱。
示例
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" ) );
}
}
}
輸出
執行該檔案,同時傳遞 --logFile 作為選項,檔案的名稱作為選項的值,並檢視結果。
java CLITester --logFile test.log test.log
Apache Commons CLI - 屬性選項
屬性選項由其名稱及其對應的屬性(如語法)在命令列中表示,這與 java 屬性檔案類似。考慮以下示例,如果我們傳遞諸如 -DrollNo = 1 -Dclass = VI -Dname = Mahesh 的選項,我們應該將每個值作為屬性進行處理。讓我們看看實際操作中的實現邏輯。
示例
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"));
}
}
}
輸出
執行該檔案,同時傳遞鍵值對作為選項,並檢視結果。
java CLITester -DrollNo = 1 -Dclass = VI -Dname = Mahesh Class: VI Roll No: 1 Name: Mahesh
Apache Commons CLI - Posix 解析器
Posix 解析器用於解析傳遞的類似 Posix 的引數。它現已棄用,並由 DefaultParser 取代。
示例
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.");
}
}
}
輸出
執行該檔案,同時傳遞 -D -A 作為選項,並檢視結果。
java CLITester -D -A D option was used. A option was used.
執行該檔案,同時傳遞 --D 作為選項,並檢視結果。
java CLITester --D D option was used.
Apache Commons CLI - GNU 解析器
GNU 解析器用於解析傳遞的類似 GNU 的引數。它現已棄用,並由 DefaultParser 取代。
示例
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"));
}
}
}
輸出
執行該檔案,同時傳遞 -p -g -n 10 作為選項,並檢視結果。
java CLITester -p -g -n 10 p option was used. g option was used. Value passed: 10
Apache Commons CLI - 使用示例
Apache Commons CLI 提供 HelpFormatter 類來列印命令列引數的使用指南。請參見下面的示例:
示例
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);
}
}
輸出
執行該檔案並檢視結果。
java CLITester usage: CLITester -g,--gui Show GUI Application -n <arg> No. of copies to print -p,--print Send print request to printer.
Apache Commons CLI - 幫助示例
Apache Commons CLI 提供 HelpFormatter 類來列印與命令列引數相關的幫助資訊。請參見示例。
示例
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();
}
}
輸出
執行該檔案並檢視結果。
java CLITester usage: CLITester [-g] [-n <arg>] [-p]