- 浏览: 141852 次
- 性别:
- 来自: 北京
文章分类
最新评论
-
zoutm:
文章写得深入浅出,顶
我们为什么要关注MapReduce? -
gongmingwind:
写的不错
Cookie的格式及组成 -
yanite:
翻译的不全,而且把不该翻译的也译了,郁闷.
HTTP/1.1 RFC2616中文 -
RStallman:
哪一个兼容性最好?最快?前提是免费的。
总结Embedding Brower JAVA API -
jiangzhx:
你好,请问你找到不带GUI,可以渲染html的工具了吗,谢谢j ...
总结Embedding Brower JAVA API
暂未翻译,链接主页http://commons.apache.org/cli/
describe some example scenarios on how to use CLI in applications.
Using a boolean option
A boolean option is represented on a command line by the presence of the option, i.e. if the option is found then the option value is true
, otherwise the value is false
.
The DateApp
utility prints the current date to standard output. If the -t
option is present the current time is also printed.
Create the Options
An Options object must be created and the Option
must be added to it.
// create Options object Options options = new Options(); // add t option options.addOption("t", false, "display current time");
The addOption
method has three parameters. The first parameter is a java.lang.String
that represents the option. The second parameter is a boolean
that specifies whether the option requires an argument or not. In the case of a boolean option (sometimes referred to as a flag) an argument value is not present so false
is passed. The third parameter is the description of the option. This description will be used in the usage text of the application.
Parsing the command line arguments
The parse
methods of CommandLineParser
are used to parse the command line arguments. The PosixPaser
is great when you need to handle options that are one character long, like the t
option in this example.
CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse( options, args);
Now we need to check if the t
option is present. To do this we will interrogate the CommandLine object. The hasOption
method takes a java.lang.String
parameter and returns true
if the option represented by the java.lang.String
is present, otherwise it returns false
.
if(cmd.hasOption("t")) { // print the date and time } else { // print the date }
International Time
The InternationalDateApp
utility extends the DateApp
utility by providing the ability to print the date and time in any country in the world. To facilitate this a new command line option, c
, has been introduced.
// add c option options.addOption("c", true, "country code");
The second parameter is true
this time. This specifies that the c
option requires an argument value. If the required option argument value is specified on the command line it is returned, otherwise null
is returned.
Retrieving the argument value
The getOptionValue
methods of CommandLine
are used to retrieve the argument values of options.
// get c option value String countryCode = cmd.getOptionValue("c"); if(countryCode == null) { // print default date } else { // print date for country specified by countryCode }
Ant Example
One of the most ubiquitous Java applications Ant will be used here to illustrate how to create the Options
required. The following is the help output for Ant.
ant [options] [target [target2 [target3] ...]] Options: -help print this message -projecthelp print project help information -version print the version information and exit -quiet be extra quiet -verbose be extra verbose -debug print debugging information -emacs produce logging information without adornments -logfile <file> use given file for log -logger <classname> the class which is to perform logging -listener <classname> add an instance of class as a project listener -buildfile <file> use given buildfile -D<property>=<value> use value for given property -find <file> search for buildfile towards the root of the filesystem and use it
Boolean Options
Lets create the boolean options for the application as they are the easiest to create. For clarity the constructors for Option
are used here.
Option help = new Option( "help", "print this message" ); Option projecthelp = new Option( "projecthelp", "print project help information" ); Option version = new Option( "version", "print the version information and exit" ); Option quiet = new Option( "quiet", "be extra quiet" ); Option verbose = new Option( "verbose", "be extra verbose" ); Option debug = new Option( "debug", "print debugging information" ); Option emacs = new Option( "emacs", "produce logging information without adornments" );
Argument Options
The argument options are created using the OptionBuilder
.
Option logfile = OptionBuilder.withArgName( "file" ) .hasArg() .withDescription( "use given file for log" ) .create( "logfile" ); Option logger = OptionBuilder.withArgName( "classname" ) .hasArg() .withDescription( "the class which it to perform " + "logging" ) .create( "logger" ); Option listener = OptionBuilder.withArgName( "classname" ) .hasArg() .withDescription( "add an instance of class as " + "a project listener" ) .create( "listener"); Option buildfile = OptionBuilder.withArgName( "file" ) .hasArg() .withDescription( "use given buildfile" ) .create( "buildfile"); Option find = OptionBuilder.withArgName( "file" ) .hasArg() .withDescription( "search for buildfile towards the " + "root of the filesystem and use it" ) .create( "find" );
Java Property Option
The last option to create is the Java property and it is also created using the OptionBuilder.
Option property = OptionBuilder.withArgName( "property=value" ) .hasArg() .withValueSeparator() .withDescription( "use value for given property" ) .create( "D" );
Create the Options
Now that we have created each Option we need to create the Options instance. This is achieved using the addOption method of Options
.
Options options = new Options(); options.addOption( help ); options.addOption( projecthelp ); options.addOption( version ); options.addOption( quiet ); options.addOption( verbose ); options.addOption( debug ); options.addOption( emacs ); options.addOption( logfile ); options.addOption( logger ); options.addOption( listener ); options.addOption( buildfile ); options.addOption( find ); options.addOption( property );
All the preperation is now complete and we are now ready to parse the command line arguments.
Create the Parser
We now need to create a Parser
. This will parse the command line arguments, using the rules specified by the Options
and return an instance of CommandLine . This time we will use a GnuParser which is able to handle options that are more than one character long.
public static void main( String[] args ) { // create the parser CommandLineParser parser = new GnuParser(); try { // parse the command line arguments CommandLine line = parser.parse( options, args ); } catch( ParseException exp ) { // oops, something went wrong System.err.println( "Parsing failed. Reason: " + exp.getMessage() ); } }
Querying the commandline
To see if an option has been passed the hasOption
method is used. The argument value can be retrieved using the getValue
method.
// has the buildfile argument been passed? if( line.hasOption( "buildfile" ) ) { // initialise the member variable this.buildfile = line.getValue( "buildfile" ); }
Usage/Help
CLI also provides the means to automatically generate usage and help information. This is achieved with the HelpFormatter class.
// automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "ant", options );
When executed the following output is produced:
usage: ant -D <property=value> use value for given property -buildfile <file> use given buildfile -debug print debugging information -emacs produce logging information without adornments -file <file> search for buildfile towards the root of the filesystem and use it -help print this message -listener <classname> add an instance of class as a project listener -logger <classname> the class which it to perform logging -projecthelp print project help information -quiet be extra quiet -verbose be extra verbose -version print the version information and exit
If you also require to have a usage statement printed then calling formatter.printHelp( "ant", options, true )
will generate a usage statment as well as the help information.
ls Example
One of the most widely used command line applications in the *nix world is ls
. To parse a command line for an application like this we will use the PosixParser . Due to the large number of options required for ls
this example will only cover a small proportion of the options. The following is a section of the help output.
Usage: ls [OPTION]... [FILE]... List information about the FILEs (the current directory by default). Sort entries alphabetically if none of -cftuSUX nor --sort. -a, --all do not hide entries starting with . -A, --almost-all do not list implied . and .. -b, --escape print octal escapes for nongraphic characters --block-size=SIZE use SIZE-byte blocks -B, --ignore-backups do not list implied entries ending with ~ -c with -lt: sort by, and show, ctime (time of last modification of file status information) with -l: show ctime and sort by name otherwise: sort by ctime -C list entries by columns
The following is the code that is used to create the Options for this example.
// create the command line parser CommandLineParser parser = new PosixParser(); // create the Options Options options = new Options(); options.addOption( "a", "all", false, "do not hide entries starting with ." ); options.addOption( "A", "almost-all", false, "do not list implied . and .." ); options.addOption( "b", "escape", false, "print octal escapes for nongraphic " + "characters" ); options.addOption( OptionBuilder.withLongOpt( "block-size" ) .withDescription( "use SIZE-byte blocks" ) .withValueSeparator( '=' ) .hasArg() .create() ); options.addOption( "B", "ignore-backups", false, "do not list implied entried " + "ending with ~"); options.addOption( "c", false, "with -lt: sort by, and show, ctime (time of last " + "modification of file status information) with " + "-l:show ctime and sort by name otherwise: sort " + "by ctime" ); options.addOption( "C", false, "list entries by columns" ); String[] args = new String[]{ "--block-size=10" }; try { // parse the command line arguments CommandLine line = parser.parse( options, args ); // validate that block-size has been set if( line.hasOption( "block-size" ) ) { // print the value of block-size System.out.println( line.getOptionValue( "block-size" ) ); } } catch( ParseException exp ) { System.out.println( "Unexpected exception:" + exp.getMessage() ); }
发表评论
-
ant start stop tomcat
2009-05-30 11:55 2571<target name="tomca ... -
暂时存记录:spring乱码过滤器
2008-11-05 22:59 1537<filter> <filt ... -
编译Google浏览器
2008-09-09 09:51 2564Google一直传言要做自己的浏览器,上周 ... -
关于http的Last-Modified和ETag
2008-09-02 17:05 21211) 什么是”Last-Modifie ... -
Http的一些编码
2008-09-01 15:43 1938HTTP Headers The headers of a H ... -
分布式Web爬虫的设计
2008-08-20 11:55 3332URL管理服务器(URL-Server):负责url的集中管理 ... -
Java 5.0的多线程类或接口
2008-08-19 17:49 1118Executor ExecutorService Callab ... -
JDK5.0 Excutor创建线程池
2008-08-19 16:11 1893import java.util.concurrent.Exe ... -
Java正则表达式
2008-08-10 13:21 1354两个问题 a. 如何知道一个url是 ... -
Java theory and practice: Dealing with Interrupte
2008-07-29 15:07 1435Many Java™ language methods, su ... -
Swing HTML显示组件
2008-07-17 10:33 6031Java Swing本身没有提供好的html显示组件,而且也不 ... -
总结Embedding Brower JAVA API
2008-07-10 11:32 3891总结一些找到的嵌入浏览器: WebRenderer 对 ... -
Cookie的格式及组成
2008-06-26 10:49 30205Cookie由变量名和值组 ... -
HTTP头信息
2008-06-25 16:24 1970HTTP的头域包括通用头,请求头,响应头和实体头四个部 ... -
HTTP Cookie & Session
2008-06-25 15:50 3790COOKIECOOKIE是大家都非常 ... -
HTTP 1.0 与 1.1比较
2008-06-25 14:32 5312一个WEB站点每天可能要接收到上百万的用户请求,为了提高系统 ... -
HTTP/1.1 RFC2616中文
2008-06-25 14:27 6604官方RFC2616文档: http://www ... -
Watij - Web Application Testing in Java
2008-05-29 16:54 2390发现一个抓取动态网页的好东东: Watij (pro ... -
Java局部线程变量---ThreadLocal
2008-05-15 16:02 6276ThreadLocal是什么 早在J ... -
Heritrix QueueAssignmentPolicy问题
2008-04-30 17:51 3792Re: [archive-crawler] Extend Qu ...
相关推荐
在具体的学习和使用过程中,SWI-Prolog提供了一个命令行交互环境,用户可以通过它快速地开始使用,执行查询,检查程序,甚至在运行时修改程序。参考手册还详细描述了如何利用用户初始化文件来定制环境,以及命令行...
中文翻译人员: 王远之 肖理达 肖盛文 黄啸宇 宋琪 陈伯乐 陈浩 陈岗 刘铭 洪建家 吴煊春 乔楚 C 1997-2011 PHP 文档组 版权信息 PHP 手册 序言 入门指引 简介 简明教程 安装与配置 安装前需要考虑的...
中文翻译人员: 王远之 肖理达 肖盛文 黄啸宇 宋琪 陈伯乐 陈浩 陈岗 刘铭 洪建家 吴煊春 乔楚 © 1997-2011 PHP 文档组 版权信息 PHP 手册 序言 入门指引 简介 简明教程 安装与配置 安装前需要考虑的...
WebSocket4J 并未实现客户端通讯协议,所以不能用它来连接 WebSocket 服务器。 Struts验证码插件 JCaptcha4Struts2 JCaptcha4Struts2 是一个 Struts2的插件,用来增加验证码的支持,使用时只需要用一个 JSP 标签 ...
中文翻译人员: 肖盛文 穆少磊 宋琪 黄啸宇 王远之 肖理达 乔楚 戴劼 © 1997-2014 PHP 文档组 •版权信息 •PHP 手册◦序言 •入门指引◦简介 ◦简明教程 •安装与配置◦安装前需要考虑的事项...
中文翻译人员: 肖盛文 穆少磊 宋琪 黄啸宇 王远之 肖理达 乔楚 戴劼 © 1997-2014 PHP 文档组 •版权信息 •PHP 手册◦序言 •入门指引◦简介 ◦简明教程 •安装与配置◦安装前需要考虑的...
中文翻译人员: 王远之 肖理达 肖盛文 黄啸宇 宋琪 陈伯乐 陈浩 陈岗 刘铭 洪建家 吴煊春 乔楚 © 1997-2011PHP 文档组 ■版权信息 ■PHP 手册■序言 ■入门指引■简介 ■简明教程 ■安装与配置■...
- **许可协议**: 该文档遵循Creative Commons Attribution-ShareAlike 2.5 license许可协议,这意味着你可以自由地复制、分发、展示和执行作品,只要给予原作者适当的署名,并且如果对作品进行了修改,则必须在相同...
中文翻译人员: 肖盛文 穆少磊 宋琪 黄啸宇 王远之 肖理达 乔楚 戴劼 © 1997-2015 PHP 文档组 •版权信息 •PHP 手册•序言 •入门指引•简介 •简明教程 •安装与配置•安装前需要考虑的事项 •Unix 系统下...
■Creative Commons Attribution 3.0 ■函数索引 ■CHM 版本 ■关于此版本 ■Using PHP Manual CHM Edition ■The Full Text Search ■Specialities of this Edition ■Integrating the PHP Manual ■Skin ...
■Creative Commons Attribution 3.0 ■函数索引 ■CHM 版本 ■关于此版本 ■Using PHP Manual CHM Edition ■The Full Text Search ■Specialities of this Edition ■Integrating the PHP Manual ■Skin ...
■Creative Commons Attribution 3.0 ■函数索引 ■CHM 版本 ■关于此版本 ■Using PHP Manual CHM Edition ■The Full Text Search ■Specialities of this Edition ■Integrating the PHP Manual ■Skin ...
中文翻译人员: 王远之 肖理达 肖盛文 黄啸宇 宋琪 陈伯乐 陈浩 陈岗 刘铭 洪建家 吴煊春 乔楚 © 1997-2011 PHP 文档组 ■版权信息 ■PHP 手册 ■序言 ■入门指引 ■简介 ■简明教程 ■安装与配置 ■...
- **编译和运行代码**:Go语言使用命令行工具进行编译和运行。文档介绍了如何设置环境并执行第一个Go程序。 - **变量、类型和保留字**:这部分内容讲解了Go语言中数据类型的定义、变量声明及初始化的方法,以及Go...
WebSocket4J 并未实现客户端通讯协议,所以不能用它来连接 WebSocket 服务器。 Struts验证码插件 JCaptcha4Struts2 JCaptcha4Struts2 是一个 Struts2的插件,用来增加验证码的支持,使用时只需要用一个 JSP 标签 ...
WebSocket4J 并未实现客户端通讯协议,所以不能用它来连接 WebSocket 服务器。 Struts验证码插件 JCaptcha4Struts2 JCaptcha4Struts2 是一个 Struts2的插件,用来增加验证码的支持,使用时只需要用一个 JSP 标签 ...
10. Apache Commons是Apache软件基金会的一个子项目,包含多个实用模块,如文件上传、命令行处理和数据库连接池等。 11. 多图幻灯播放组件通常使用JavaScript脚本和CSS样式来控制图片的自动切换效果。 12. 在Servlet...
- **命令行编译任务**:介绍了如何通过命令行工具进行编译。 - **开发环境**:推荐使用 Eclipse IDE 进行开发。 - **生产环境**:在生产环境中使用 Ant 进行构建。 **5.8 从源代码构建** - **安装 Subversion**:...
WebSocket4J 并未实现客户端通讯协议,所以不能用它来连接 WebSocket 服务器。 Struts验证码插件 JCaptcha4Struts2 JCaptcha4Struts2 是一个 Struts2的插件,用来增加验证码的支持,使用时只需要用一个 JSP 标签 ...