CLI是Jakarta Commons中的一個子類。如果你僅僅只有一到兩個參數需要處理,那麼使用它有點多餘,但是,如果你需要從命令列中捕獲大多數應用程式的設定參數,那麼使用CLI是恰到好處的。
在使用CLI之前需要建立一個Options對象,該對象相當於一個容器,另外還有Option對象,每個Option對象相對於命令列中的一個參數。
Options opts = new Options();
通過利用這個Options,你可以使用addOption()方法定義你的應用程式可接受的命令列參數,每次都為一個option調用一次這個方法,看下面例示:
opts.addOption("h", false, "Print help for this application");
opts.addOption("u", true, "The username to use");
opts.addOption("dsn", true, "The data source to use");
當然你也可以單獨建立Option對線,然後使用addOption()方法添加進去。如下:
Option op = new Option("h", false, "Print help for this application");
一旦你定義了類的參數,建立一個CommandLineParser,並分析已傳送到主方法中的組。
BasicParser parser = new BasicParser();
CommandLine cl = parser.parse(opts, args);
等到所有的參數都被解析以後,你可以開始檢查返回的命令列,這些命令列中,提供使用者的參數和值已被文法剖析器詳細檢查過了。
if (cl.hasOption('h')) {
HelpFormatter hf = new HelpFormatter();
hf.printHelp("OptionsTip", opts);
} else {
System.out.println(cl.getOptionValue("u"));
System.out.println(cl.getOptionValue("dsn"));
}
就象你看到的那樣,你可以使用HelpRormatter類為你的程式自動地產生使用資訊。
下面看一下全部的代碼:
package com.founder.common;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public class OptionsTip {
public static void main(String[] args) {
try {
Options opts = new Options();
opts.addOption("h", false, "Print help for this application");
opts.addOption("u", true, "The username to use");
opts.addOption("dsn", true, "The data source to use");
BasicParser parser = new BasicParser();
CommandLine cl = parser.parse(opts, args);
if (cl.hasOption('h')) {
HelpFormatter hf = new HelpFormatter();
hf.printHelp("OptionsTip", opts);
} else {
System.out.println(cl.getOptionValue("u"));
System.out.println(cl.getOptionValue("dsn"));
}
} catch (ParseException pe) {
pe.printStackTrace();
}
}
}
註:使用此程式時候別忘了把commons-cli-1.0.jar加入到你的classpath中
運行結果:
E:/javaworkspace/collection/src>java com.founder.common.OptionsTip -h
usage: OptionsTip
-dsn The data source to use
-h Print help for this application
-u The username to use
E:/javaworkspace/collection/src>java com.founder.common.OptionsTip -u eric -dsn founder
eric
founder
文章轉載自
http://www.blogjava.net/rain1102/archive/2008/04/16/193521.html