Jakarta-Common-CLI使用笔记
时间:2011-01-28 csdn博客 沈斌
这是一个处理处理命令的工具。比如main方法输入的string[]需要解析。你可以预先定义好参数的规则,然后就可以调用CLI来解析。
下载地址:http://commons.apache.org/downloads/download_cli.cgi
如下为使用cli生成命令行注释的演示代码:
package demo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
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) ...{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
try ...{
args = in.readLine().split(" ");
Options opt = new Options();
opt.addOption("h", false, "Print help for this application");
opt.addOption("u", true, "The username to use");
opt.addOption("dsn", true, "The data source to use");
BasicParser parser = new BasicParser();
CommandLine cl = parser.parse(opt, args);
if (cl.hasOption(''h'')) ...{
HelpFormatter f = new HelpFormatter();
f.printHelp("OptionsTip", opt);
} else ...{
System.out.println(cl.getOptionValue("u"));
System.out.println(cl.getOptionValue("dsn"));
}
} catch (ParseException e) ...{
e.printStackTrace();
} catch (IOException e) ...{
e.printStackTrace();
}
}
} 上诉代码运行后在控制台输入 -h,显示如下信息:
usage: OptionsTip
-dsn <arg> The data source to use
-h Print help for this application
-u <arg> The username to use
|