`
sole
  • 浏览: 141551 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Commons 命令行接口使用(未翻译)

阅读更多

暂未翻译,链接主页http://commons.apache.org/cli/

describe some example scenarios on how to use CLI in applications.

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.

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

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() );
    }
}

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() );
}
分享到:
评论

相关推荐

    SWI-Prolog-7.6.4英文教程

    在具体的学习和使用过程中,SWI-Prolog提供了一个命令行交互环境,用户可以通过它快速地开始使用,执行查询,检查程序,甚至在运行时修改程序。参考手册还详细描述了如何利用用户初始化文件来定制环境,以及命令行...

    php5中文手册20111124

    中文翻译人员: 王远之 肖理达 肖盛文 黄啸宇 宋琪 陈伯乐 陈浩 陈岗 刘铭 洪建家 吴煊春 乔楚 C 1997-2011 PHP 文档组 版权信息 PHP 手册 序言 入门指引 简介 简明教程 安装与配置 安装前需要考虑的...

    php中文手册

    中文翻译人员: 王远之 肖理达 肖盛文 黄啸宇 宋琪 陈伯乐 陈浩 陈岗 刘铭 洪建家 吴煊春 乔楚 © 1997-2011 PHP 文档组 版权信息 PHP 手册 序言 入门指引 简介 简明教程 安装与配置 安装前需要考虑的...

    java开源包10

    WebSocket4J 并未实现客户端通讯协议,所以不能用它来连接 WebSocket 服务器。 Struts验证码插件 JCaptcha4Struts2 JCaptcha4Struts2 是一个 Struts2的插件,用来增加验证码的支持,使用时只需要用一个 JSP 标签 ...

    php5.5.10中文手册下载[官方版][2014-02-20最后编译]

    中文翻译人员: 肖盛文 穆少磊 宋琪 黄啸宇 王远之 肖理达 乔楚 戴劼 © 1997-2014 PHP 文档组 •版权信息 •PHP 手册◦序言 •入门指引◦简介 ◦简明教程 •安装与配置◦安装前需要考虑的事项...

    php5.5.10手册官方版【2014-02-20编译】

    中文翻译人员: 肖盛文 穆少磊 宋琪 黄啸宇 王远之 肖理达 乔楚 戴劼 © 1997-2014 PHP 文档组 •版权信息 •PHP 手册◦序言 •入门指引◦简介 ◦简明教程 •安装与配置◦安装前需要考虑的...

    php参考手册

    中文翻译人员: 王远之 肖理达 肖盛文 黄啸宇 宋琪 陈伯乐 陈浩 陈岗 刘铭 洪建家 吴煊春 乔楚 © 1997-2011PHP 文档组 ■版权信息 ■PHP 手册■序言 ■入门指引■简介 ■简明教程 ■安装与配置■...

    unix_linux_introduction.pdf

    - **许可协议**: 该文档遵循Creative Commons Attribution-ShareAlike 2.5 license许可协议,这意味着你可以自由地复制、分发、展示和执行作品,只要给予原作者适当的署名,并且如果对作品进行了修改,则必须在相同...

    PHP 5.4.40 Released 中文手册

    中文翻译人员: 肖盛文 穆少磊 宋琪 黄啸宇 王远之 肖理达 乔楚 戴劼 © 1997-2015 PHP 文档组 •版权信息 •PHP 手册•序言 •入门指引•简介 •简明教程 •安装与配置•安装前需要考虑的事项 •Unix 系统下...

    最新PHP中文手册7月1号php_manual_zh.part3.rar

    ■Creative Commons Attribution 3.0 ■函数索引 ■CHM 版本 ■关于此版本 ■Using PHP Manual CHM Edition ■The Full Text Search ■Specialities of this Edition ■Integrating the PHP Manual ■Skin ...

    最新PHP中文手册7月1号php_manual_zh.part1.rar

    ■Creative Commons Attribution 3.0 ■函数索引 ■CHM 版本 ■关于此版本 ■Using PHP Manual CHM Edition ■The Full Text Search ■Specialities of this Edition ■Integrating the PHP Manual ■Skin ...

    最新PHP中文手册7月1号php_manual_zh.part4.rar

    ■Creative Commons Attribution 3.0 ■函数索引 ■CHM 版本 ■关于此版本 ■Using PHP Manual CHM Edition ■The Full Text Search ■Specialities of this Edition ■Integrating the PHP Manual ■Skin ...

    php5中文版20110401编译

    中文翻译人员: 王远之 肖理达 肖盛文 黄啸宇 宋琪 陈伯乐 陈浩 陈岗 刘铭 洪建家 吴煊春 乔楚 © 1997-2011 PHP 文档组 ■版权信息 ■PHP 手册 ■序言 ■入门指引 ■简介 ■简明教程 ■安装与配置 ■...

    java开源包1

    WebSocket4J 并未实现客户端通讯协议,所以不能用它来连接 WebSocket 服务器。 Struts验证码插件 JCaptcha4Struts2 JCaptcha4Struts2 是一个 Struts2的插件,用来增加验证码的支持,使用时只需要用一个 JSP 标签 ...

    java开源包8

    WebSocket4J 并未实现客户端通讯协议,所以不能用它来连接 WebSocket 服务器。 Struts验证码插件 JCaptcha4Struts2 JCaptcha4Struts2 是一个 Struts2的插件,用来增加验证码的支持,使用时只需要用一个 JSP 标签 ...

    JAVA组件复习资料.pdf

    10. Apache Commons是Apache软件基金会的一个子项目,包含多个实用模块,如文件上传、命令行处理和数据库连接池等。 11. 多图幻灯播放组件通常使用JavaScript脚本和CSS样式来控制图片的自动切换效果。 12. 在Servlet...

    Openbravo技术评测

    - **命令行编译任务**:介绍了如何通过命令行工具进行编译。 - **开发环境**:推荐使用 Eclipse IDE 进行开发。 - **生产环境**:在生产环境中使用 Ant 进行构建。 **5.8 从源代码构建** - **安装 Subversion**:...

    java开源包11

    WebSocket4J 并未实现客户端通讯协议,所以不能用它来连接 WebSocket 服务器。 Struts验证码插件 JCaptcha4Struts2 JCaptcha4Struts2 是一个 Struts2的插件,用来增加验证码的支持,使用时只需要用一个 JSP 标签 ...

Global site tag (gtag.js) - Google Analytics