Commons CLI - Usage
Usage Scenarios
The following sections 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. There may be several implementations of the CommandLineParser interface, the recommended one is the DefaultParser.
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse( options, args);
Now we need to check if the t option is present. To do this we will interrogate the CommandLineobject. The hasOption method takes a java.lang.String parameter and returnstrue if the option represented by the java.lang.String is present, otherwise it returns false.
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 printthis message
-projecthelp print project help information
-version print the version information andexit
-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 classas 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 anduse 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" )
.hasArgs(2)
.withValueSeparator()
.withDescription( "use value for given property" )
.create( "D" );
The map of properties specified by this option can later be retrieved by calling getOptionProperties("D") on the CommandLine.
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 CommandLineParser. This will parse the command line arguments, using the rules specified by the Options and return an instance of CommandLine.
public static void main( String[] args ) {
// create the parser
CommandLineParser parser = new DefaultParser();
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 getOptionValue method.
// has the buildfile argument been passed?
if( line.hasOption( "buildfile" ) ) {
// initialise the member variable
this.buildfile = line.getOptionValue( "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 anduse it
-help printthis message
-listener <classname> add an instance of classas 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 andexit
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. 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 bydefault).
Sort entries alphabetically if none of -cftuSUX nor --sort. -a,--all donot hide entries starting with.
-A,--almost-all donot list implied .and..
-b,--escape print octal escapes for nongraphic characters
--block-size=SIZE use SIZE-byte blocks
-B,--ignore-backups donot 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 DefaultParser(); // 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" )
.hasArg()
.withArgName("SIZE")
.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() );
}
Commons CLI - Usage的更多相关文章
- Apache Commons CLI官方文档翻译 —— 快速构建命令行启动模式
昨天通过几个小程序以及Hangout源码学习了CLI的基本使用,今天就来尝试翻译一下CLI的官方使用手册. 下面将会通过几个部分简单的介绍CLI在应用中的使用场景. 昨天已经联系过几个基本的命令行参数 ...
- Apache Commons CLI命令行启动
今天又看了下Hangout的源码,一般来说一个开源项目有好几种启动方式--比如可以从命令行启动,也可以从web端启动.今天就看看如何设计命令行启动... Apache Commons CLI Apac ...
- Commons CLI 学习(1)
The Apache Commons CLI library provides an API for parsing command line options passed to programs. ...
- Apache Commons CLI 简介
CLI 命令代码实现 命令行程序处理流程相对比较简单,主要流程为设定命令行参数 -> 解析输入参数 -> 使用输入的数据进行逻辑处理CLI 定义阶段 每一条命令行都必须定义一组参数,它们被 ...
- Apache Commons CLI 开发命令行工具示例
概念说明Apache Commons CLI 简介 虽然各种人机交互技术飞速发展,但最传统的命令行模式依然被广泛应用于各个领域:从编译代码到系统管理,命令行因其简洁高效而备受宠爱.各种工具和系统都 提 ...
- 使用commons.cli实现MyCP
目录 Commons.cli库 MyCP 测试代码 总结 Commons.cli库 考虑到这次的任务是实现自己的命令行命令cp,我认为简单地使用args[]无法很好的完成需求.经过网上的一番搜索,我找 ...
- The type org.apache.commons.cli.Options cannot be resolved. It is indirectly referenced from required .class files
在搭建好Hadoop Eclipse开发环境后,编写map-reduce,遇到如下的问题: 从字面上可以看出,工程缺少org.apache.commons.cli.Options,这个包被间接的被其他 ...
- 使用 Apache Commons CLI 开发命令行工具示例
Apache Commons CLI 简介 Apache Commons CLI 是 Apache 下面的一个解析命令行输入的工具包,该工具包还提供了自动生成输出帮助文档的功能. Apache Com ...
- 使用 Apache Commons CLI 解析命令行参数示例
很好的输入参数解析方法 ,转载记录下 转载在: https://www.cnblogs.com/onmyway20xx/p/7346709.html Apache Commons CLI 简介 Apa ...
随机推荐
- flask前后台交互数据的几个思路
通过url进行参数传递: @app.route('/hello/<name>') # <name>为传递的参数 def hello(name=None): return ren ...
- Python多线程学习资料1
一.Python中的线程使用: Python中使用线程有两种方式:函数或者用类来包装线程对象. 1. 函数式:调用thread模块中的start_new_thread()函数来产生新线程.如下例: ...
- Unity3D细节整理:AssetBundle对应的各种格式文件的类型
我们打包AssetBundle后,Unity3D会根据文件的后缀名将文件转换为特定的类型对象存储起来,我们后期获取时需要根据这些类型取出打包的数据,这里记录下不同后缀文件打包后的类型. 文本格式 支持 ...
- 【转】Watir, Selenium & WebDriver
转自:http://watirmelon.com/2010/04/10/watir-selenium-webdriver/ Please also see my new ‘Watir-WebDrive ...
- 2015 NOIP day1 t1 神奇的幻方 模拟
神奇的幻方 Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://www.luogu.org/problem/show?pid=2615 Descri ...
- range-bar
https://github.com/edmodo/range-bar
- 用VS2010开发Android应用的配置方法
在开发你的第一个Android应用程序之前,你应该先检查一下是否安装了Android SDK,以及是否创建好了Android模拟器(AVD),如果有不清楚的地方,请先看百度这篇文章“Android是什 ...
- JNI 系统钩子
占个位置,日后学会了补充: JAVA是运行在虚拟机上的,而钩子函数是直接对操作系统进行操作控制的,这也是Java和C的主要区别之一,Java要实现钩子函数比较麻烦,需要使用JNI技术,就是Java本地 ...
- iOS开发——UI篇&文字渐变效果:图层中的mask属性
文字渐变效果:图层中的mask属性 本次文章,主要讲述的是图层中的mask属性,利用它,可以做出文字渐变效果! 一.文字渐变效果: 二.文字渐变实现思路: 1.创建一个颜色渐变层,渐变图层跟文字控件一 ...
- 使用proguard混淆android代码
当前是有些工具比方apktool,dextojar等是能够对我们android安装包进行反编译,获得源代码的.为了降低被别人破解,导致源代码泄露,程序被别人盗代替码,等等.我们须要对代码进行混淆,an ...