Commons CLI

	<dependency>
			<groupId>commons-cli</groupId>
			<artifactId>commons-cli</artifactId>
			<version>1.5.0</version>
		</dependency>

使用 Commons CLI,需要经过以下几个步骤:

  1. 创建 Options 对象

Options 对象用于定义命令行选项。需要根据需求添加相应的选项,并设置其属性并添加描述信息。

		Options options = new Options();
 
		;
 		options.addOption(Option.builder("i").longOpt("input").hasArg(true).desc("input file path").hasArg().required().build());
 		options.addOption(Option.builder("o").longOpt("output").hasArg(true).desc("output file path").hasArg().required().build());

在这个示例中,我们创建了两个选项,一个是必填的搜索关键字选项,另一个是可选的请求页码选项。

  1. 解析用户输入

使用 CommandLineParser 对象解析用户传入的参数,该对象接收 Options 对象和命令行参数数组,并返回一个 CommandLine 对象,该对象表示用户输入的选项和参数。

	CommandLineParser parser = new DefaultParser();
		HelpFormatter formatter = new HelpFormatter();
		CommandLine cmd;

		try {
			cmd = parser.parse(options, args);
		} catch (ParseException e) {
			System.out.println(e.getMessage());
			formatter.printHelp("utility-name", options);

			System.exit(1);
			return;
		}

在解析命令行参数时,若发生异常,则会抛出 ParseException 异常,需要在代码中进行处理。

  1. 获取选项值

从 CommandLine 对象获取选项值,执行相应的业务逻辑。

	String inputFilePath = cmd.getOptionValue("input");
 		String outputFilePath = cmd.getOptionValue("output");
		System.out.println(inputFilePath);
		System.out.println(outputFilePath);

在这个示例中,我们首先获取必填的搜索关键字选项,然后获取可选的请求页码选项,若请求页码未提供,则默认为 1。

使用 Commons CLI 可以方便地解析命令行参数,并根据解析后的结果执行相应的操作,使命令行工具更加易用和用户友好。

打包然后:cmd中:
java -jar todo.jar -i D:\todo -o D:\todo\target

posted @ 2023-05-16 11:07  三号小玩家  阅读(104)  评论(0)    收藏  举报
Title
三号小玩家的 Mail: 17612457115@163.com, 联系QQ: 1359720840 微信: QQ1359720840