HOWTO · Java

Java 中的命令列解析

本文介紹 Java 中的命令列解析

本頁內容

本文介紹如何在 java 中執行命令列解析。

Java 中的命令列解析

有時,要執行 Java 程式,我們需要在執行程式之前進行一些基本輸入。通常,這些輸入由命令列引數提供。在 Java 中,命令列引數儲存在 main() 函式內的 String[] args 中。

為了從終端/命令提示符接受引數,我們需要在 Java 程式中定義選項。你傳遞的每個命令列引數都需要儲存在選項中。在下面的程式碼示例中,建立的兩個選項涉及複製和貼上現象。請看說明。

import org.apache.commons.cli.*;
public class Main {
  public static void main(String[] args) throws Exception {
    Options options = new Options(); // Options Arguments which are Acceptable By Program.
    Option source = new Option("s", "source", true, "source file path");
    source.setRequired(true);
    options.addOption(source);
    Option destination = new Option("d", "Destination", true, "Destination file Path");
    destination.setRequired(true);
    options.addOption(destination);

    CommandLineParser parser = new BasicParser();
    // use to read Command Line Arguments
    HelpFormatter formatter = new HelpFormatter(); // // Use to Format
    CommandLine cmd = null;

    try {
      cmd = parser.parse(
          options, args); // it will parse according to the options and parse option value
    } catch (ParseException e) {
      System.out.println(e.getMessage());
      formatter.printHelp("utility-name", options);

      System.exit(1);
    }

    String argument1 = cmd.getOptionValue("source");
    String argument2 = cmd.getOptionValue("Destination");

    System.out.println(argument1);
    System.out.println(argument2);
  }
}

在上面的程式中建立了兩個選項。一個是源頭,一個是目的地。在建立 source 選項時,我們將其短期引數指定為 s 並將其命名為 source。s 是獲取源引數值的命令。執行程式時,使用者必須使用 -s 作為命令,後跟其值。請參閱下面的輸出。我們還將要求設定為 true 並將描述作為原始檔路徑。後來我們在選項中新增了這個源選項引數。同樣,對於選項 destination,我們執行了具有不同值的相同操作。

在解析這兩個選項時,我們建立了一個 CommandLineParser 物件。在 HelpFormatter 的幫助下,如果需要顯示異常,我們可以格式化命令引數。

在 try...catch 方法中,使用 parse() 來解析引數 options 和 args。然後我們簡單地使用 getOptionValue() 獲取選項的值並在括號內傳遞選項的名稱。

我們只是列印值。另一方面,你可以使用這種方法執行不同的程式。

要執行該程式,我們必須使用以下命令。

javac
    - cp 'org.apache.commons.cli-1.2.0.jar' Main.java

          java
    - cp 'org.apache.commons.cli-1.2.0.jar' Main.java - s 'D://textfile.txt'
    - d 'D://DuplicatFolder//'

這裡,-s 和 -d 是命令。它們後面分別是它們的值。例如,在上面的程式中,我們將為 s 放置源路徑,為 d 放置目標路徑。

上面的程式將給出以下輸出。

D : // textfile.txt
    D: // DuplicatFolder//