JAVA 命令行参数解析,org.apache.commons.cli的使用
- maven依赖引入
<dependency> <groupId>commons-cli</groupId> <artifactId>commons-cli</artifactId> <version>1.2</version> </dependency>
- 示例代码,以下是从命令行读取文件路径的例子
private static void main(String[] args) { final Options options = new Options(); final Option option = new Option("f", true, "Configuration file path"); options.addOption(option); final CommandLineParser parser = new PosixParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (final ParseException e) { throw new Exception("parser command line error",e); } String configFilePath = null; if (cmd.hasOption("f")) { configFilePath = cmd.getOptionValue("f"); }else{ System.err.println("please input the configuration file path by -f option"); System.exit(1); } if (StringUtils.isBlank(configFilePath)) { throw new Exception("Blank file path"); } return configFilePath; }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步