Commons CLI使用

原来粗略的浏览过apache Commons CLI,今天有个项目用到了,竟然没有印象,又重新浏览了一下,在此纪录一下。
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("--------------------------------------");

	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值