Commons CLI使用
2016-01-14 15:28
369 查看
原来粗略的浏览过apache Commons CLI,今天有个项目用到了,竟然没有印象,又重新浏览了一下,在此纪录一下。
Apache Commons CLI library为用户提供了一个解释命令行的API.它在解释命令行时主要有三个状态,即:定义、解释和询问交互。
代码如下,具体实现通过注释表示:
Apache Commons CLI library为用户提供了一个解释命令行的API.它在解释命令行时主要有三个状态,即:定义、解释和询问交互。
代码如下,具体实现通过注释表示:
package com.apache.common.cli.demo; import java.util.List; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import com.Utils; public class ApaCliDemo { public static void main(String[] args) throws Exception { //1。访问参数必须加-,如果不加则认为是前一参数的value,也可以写在一起,用空格隔开 //2.参数不能有空格,否则commandLine.getOptionValue(name.trim())获取不到值,commandLine.getArgList()则能获取到值(原因没有仔细看) String arg[] = { "-h", "-s", "-r","nameOne nameTwo", "-start" ,"-x", "helloWord"}; // String arg[] = { "-h", "-s", "-r nameOne nameTwo", "-start" ,"-x", "helloWord"}; testOptions(arg); } public static void testOptions(String[] args) throws ParseException { // CLI定义 Options option = new Options(); option.addOption("h","help", false, "this is help"); option.addOption("start","start-all", false, "this app is start ...."); option.addOption("stop","stop-all", false, "this app is stop ...."); option.addOption("s", "stop-all", false, "this app is stop ...."); option.addOption("r", "run", true, "this app is stop ...."); option.addOption("x", "rsn", true, "this app is stop ...."); // CLI的解析 CommandLineParser parser = new PosixParser(); CommandLine commandLine = null; HelpFormatter hf = new HelpFormatter(); hf.setWidth(110); try { commandLine = parser.parse(option, args); } catch (Exception e) { hf.printHelp("test", option, true); System.err.println(e.getLocalizedMessage()); return; } // CLI询问 if (commandLine.hasOption("h")) { List<?> list = commandLine.getArgList(); args = commandLine.getArgs(); Utils.printList(list); System.out.println("h execte..."); } // 打印opts的名称和值 System.out.println("--------------------------------------"); Option[] opts = commandLine.getOptions(); if (opts != null) { for (Option opt1 : opts) { String name = opt1.getOpt(); String value = commandLine.getOptionValue(name.trim()); System.out.println(name + "=>" + value); } } System.out.println("--------------------------------------"); } }
相关文章推荐
- WPF Issues
- js实例代码
- MySQL innodb表空间
- Android隐藏标题状态栏的方法
- Ubuntu出现error:unknown filesystem grub rescue解决办法
- iphone导入通讯录
- 获取sevlet response值
- 导航显示问题
- 创建型模式5之2-AbstractFactory抽象工厂模式例子理解
- Git协作流程
- Android 模仿网易新闻简单标题栏 《零基础学安卓》
- HttpURLConnection的流式输出的缺陷和解决方法
- WebViewJavascriptBridge使用分析(二)
- Controller生命周期
- 在Unity中使用UGUI修改Mesh绘制几何图形
- mysql 存储过程,搞死人的语法
- 极光推送
- 2.3静态synchronized同步方法和synchronized(class)代码块
- 虚拟机上迁移Linux系统
- Can't connect to local MySQL server through socke