CLI是Jakarta Commons中的一個(gè)子類。如果你僅僅只有一到兩個(gè)參數(shù)需要處理,那么使用它有點(diǎn)多余,但是,如果你需要從命令行中捕獲大多數(shù)應(yīng)用程序的設(shè)置參數(shù),那么使用CLI是恰到好處的。
在使用CLI之前需要?jiǎng)?chuàng)建一個(gè)Options對(duì)象,該對(duì)象相當(dāng)于一個(gè)容器,另外還有Option對(duì)象,每個(gè)Option對(duì)象相對(duì)于命令行中的一個(gè)參數(shù)。
Options opts = new Options();
通過(guò)利用這個(gè)Options,你可以使用addOption()方法定義你的應(yīng)用程序可接受的命令行參數(shù),每次都為一個(gè)option調(diào)用一次這個(gè)方法,看下面例示:
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");
當(dāng)然你也可以單獨(dú)創(chuàng)建Option對(duì)線,然后使用addOption()方法添加進(jìn)去。如下:
Option op = new Option("h", false, "Print help for this application");
一旦你定義了類的參數(shù),創(chuàng)建一個(gè)CommandLineParser,并分析已傳送到主方法中的組。
BasicParser parser = new BasicParser();
CommandLine cl = parser.parse(opts, args);
等到所有的參數(shù)都被解析以后,你可以開(kāi)始檢查返回的命令行,這些命令行中,提供用戶的參數(shù)和值已被語(yǔ)法分析程序詳細(xì)檢查過(guò)了。
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類為你的程序自動(dòng)地產(chǎn)生使用信息。
下面看一下全部的代碼:
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();
}
}
}
注:使用此程序時(shí)候別忘了把commons-cli-1.0.jar加入到你的classpath中
運(yùn)行結(jié)果:
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
posted on 2008-04-16 17:31
周銳 閱讀(2249)
評(píng)論(0) 編輯 收藏 所屬分類:
Apache