java命令行解析库_Java命令行解析:apache commons-cli
发布日期:2022-02-03 15:24:57 浏览次数:6 分类:技术文章

本文共 1629 字,大约阅读时间需要 5 分钟。

Apache Commons CLI用于解析命令行选项,也可以输出详细的选项说明信息。

Commons CLI 支持多种选项类型:

POSIX like options (ie. tar -zxvf foo.tar.gz)

GNU like long options (ie. du --human-readable --max-depth=1)

Java like properties (ie. java -Djava.awt.headless=true -Djava.net.useSystemProxies=true Foo)

Short options with value attached (ie. gcc -O2 foo.c)

long options with single hyphen (ie. ant -projecthelp)

Commons CLI处理过程可以分成三个阶段

定义阶段,Options类。

解析阶段,使用CommandLineParser类讲String[] args解析为CommandLine

查询阶段,调用CommandLine对象的方法,查询和提取特定选项。

命令行选型定义

Options options = new Options();

options.addOption("h", "help", false, "Print this usage information");

options.addOption("v", "verbose", false, "Print out VERBOSE information" );

options.addOption("p", false, "no error if existing, make parent directories as needed.");

options.addOption(OptionBuilder.withArgName("file")

.hasArg()

.withDescription("search for buildfile towards the root of the filesystem and use it")

.create("O"));

options.addOption(OptionBuilder.withLongOpt("block-size")

.withDescription("use SIZE-byte blocks")

.withValueSeparator('=')

.hasArg()

.create() );

解析

CommandLineParser parser = new BasicParser( );

CommandLineParser parser = new PosixParser();

CommandLine commandLine = parser.parse( options, args );

选型查询和提取

if( commandLine.hasOption('f') ) {

file = commandLine.getOptionValue('f');

}

String[] str = commandLine.getArgs();

显示帮助信息

HelpFormatter formatter = new HelpFormatter();

formatter.printHelp("xxcmd [-lkjs] PATH", "", options , "");

formatter.printHelp( "ant", options );

formatter.printHelp( "ant", options, true ); //generate a usage statment as well as the help information

转载地址:https://blog.csdn.net/weixin_35600779/article/details/114133685 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:java环形队列_环形队列高效触发大量超时任务的算法实现
下一篇:java gui 结构_java GUI编程

发表评论

最新留言

关注你微信了!
[***.104.42.241]2024年04月16日 21时54分56秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章