Apache commons CLI介紹和簡單應用

來源:互聯網
上載者:User

標籤:apache   java   原始碼   cli   

CLI 即Command Line Interface,也就是"命令列介面",它為Java 程式訪問和解析命令列參數提供了一種統一的介面。

apache Commons CLI為使用者提供了一個解釋命令列的API.

它在解釋命令列時主要有三個狀態,即:定義、解釋和詢問互動。

 

通過使用commons cli則可以很容易的訪問參數,而不必去迴圈String[] args。

這個命令需要類比命令列輸入,可以將應用做成jar檔案後輸入命令列執行,也可以將命令列封裝成參數執行。

在eclipse下運行則需要通過Run as /runConfigurations/Arguments來進行命令列參數配置 

在MyEclipse中運行此類,在工程樹中按右鍵該類選擇Run As --> Run Configurations ... --> 選擇第二個面板[(x)=Arguments] --> 在Program arguments

 

輸入參數: -p 範芳銘 -t time –h

 

用apacheCommons CLI實現的一個簡單的範例程式碼如下:

packagetest.ffm83.commons.CLI;

 

importjava.util.Date;

 

importorg.apache.commons.cli.CommandLine;

importorg.apache.commons.cli.CommandLineParser;

importorg.apache.commons.cli.Options;

importorg.apache.commons.cli.PosixParser;

/**

 * 通過commons CLI進行簡單的命令列輸入

 * @author 範芳銘

 */

publicclass EasyCLIUsage {

    public static void main(String[] args)throws Exception {

        Options options = new Options(); 

        //true 需要帶參數,false 不用參數

        options.addOption("t", true,"display current time");//參數不可用    

        options.addOption("p", true,"person owner");//參數可用    

        options.addOption("h", false,"help");//參數可用    

   

        CommandLineParser parser = newPosixParser();  

        CommandLine cmd = parser.parse(options,args);    

   

        if (cmd.hasOption("p")){    

            String code =cmd.getOptionValue("p");    

            System.out.println("輸入參數 p:" + code);    

        }    

   

        if (cmd.hasOption("t")){    

            String code =cmd.getOptionValue("t");    

            System.out.println("輸入參數t:" + code + "," +new Date());    

        } 

       

        if (cmd.hasOption("h")){      

            System.out.println("輸入參數h:協助:[-t][-c][-h]");    

        } 

    }

}

 

運行後結果為:

 

輸入參數 p:範芳銘

輸入參數t:time,Tue Dec 30 09:23:38 CST 2014

輸入參數h:協助:[-t][-c][-h]

Apache commons CLI介紹和簡單應用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.