Java命令行解析工具Apache CLI
出处:http://blog.csdn.net/conquer0715/article/details/42805947Apache Commons CLI 是 Apache 下面的一个解析命令行输入的工具包,该工具包还提供了自动生成输出帮助文档的功能。
Apache Commons CLI 支持多种输入参数格式,主要支持的格式有以下几种:
[*]POSIX(Portable Operating System Interface of Unix)中的参数形式,例如 tar -zxvf foo.tar.gz
[*]GNU 中的长参数形式,例如 du --human-readable --max-depth=1
[*]Java 命令中的参数形式,例如 java -Djava.net.useSystemProxies=true Foo
[*]短杠参数带参数值的参数形式,例如 gcc -O2 foo.c
[*]长杠参数不带参数值的形式,例如 ant – projecthelp
随着科学计算可视化及多媒体技术的飞速发展,人机交互技术不断更新,但是最传统的命令行模式依然被广泛的应用于多个领域,因为命令行界面要较图形用户界面节约更多的计算机系统资源。在熟记命令的前提下,使用命令行界面往往要较使用图形用户界面的操作速度要快。同时,命令行模式也更加有利于客户进行二次开发,方便应用程序的整合。Apache Commons CLI 提供了很多实用的工具和类实现,进一步方便了我们对命令行工具的开发。
view plaincopyhttp://onexin.iyunv.com/source/plugin/onexin_bigdata/https://code.csdn.net/assets/CODE_ico.pnghttp://onexin.iyunv.com/source/plugin/onexin_bigdata/https://code.csdn.net/assets/ico_fork.svg
[*]import org.apache.commons.cli.*;
[*]
[*]public class Test {
[*]
[*] public static void main(String[] args) throws ParseException {
[*] // for test
[*] String[] Args0 = {"-h"};
[*] String[] Args1 = {"-i", "192.168.1.1", "-p", "8443", "-t", "https"};
[*]
[*] Option help = new Option("h", "the command help");
[*] Option user = OptionBuilder.withArgName("type").hasArg().withDescription("target the search type").create("t");
[*]
[*] // 此处定义参数类似于 java 命令中的 -D<name>=<value>
[*] Option property = OptionBuilder.withArgName("property=value").hasArgs(2).withValueSeparator().withDescription
[*] ("search the objects which have the target property and value").create("D");
[*] Options opts = new Options();
[*] opts.addOption(help);
[*] opts.addOption(user);
[*] opts.addOption(property);
[*]
[*] // do test
[*]// simpleTest(args);
[*] simpleTest(Args1);
[*] }
[*]
[*] /////////
[*]
[*] public static void simpleTest(String[] args) {
[*] Options opts = new Options();
[*] opts.addOption("h", false, "HELP_DESCRIPTION");
[*] opts.addOption("i", true, "HELP_IPADDRESS");
[*] opts.addOption("p", true, "HELP_PORT");
[*] opts.addOption("t", true, "HELP_PROTOCOL");
[*] CommandLineParser parser = new BasicParser();
[*]// CommandLineParser parser = new GnuParser ();
[*]// CommandLineParser parser = new PosixParser();
[*] CommandLine cl;
[*] try {
[*] cl = parser.parse(opts, args);
[*] if (cl.getOptions().length > 0) {
[*] if (cl.hasOption('h')) {
[*] HelpFormatter hf = new HelpFormatter();
[*] hf.printHelp("May Options", opts);
[*] } else {
[*] String ip = cl.getOptionValue("i");
[*] String port = cl.getOptionValue("p");
[*] String protocol = cl.getOptionValue("t");
[*] System.out.println(ip);
[*] System.out.println(port);
[*] System.out.println(protocol);
[*] }
[*] } else {
[*] System.err.println("ERROR_NOARGS");
[*] }
[*] } catch (ParseException e) {
[*] e.printStackTrace();
[*] }
[*] }
[*]}
页:
[1]