scala解析命令行参数

如何用scala解析命令行参数:

首先,需要在项目中添加Apache Commons CLI库的依赖。可以在build.sbt文件中添加如下行:

libraryDependencies += "commons-cli" % "commons-cli" % "1.4"

Scala 复制代码
import org.apache.commons.cli.{Options, CommandLineParser, DefaultParser, HelpFormatter, ParseException}

object CommandLineParserExample {

  def main(args: Array[String]): Unit = {
    // 创建Options对象,用于存储命令行选项
    val options = new Options()
    options.addOption("h", "help", false, "显示帮助信息")
    options.addOption("f", "file", true, "指定文件路径")

    // 创建命令行解析器
    val parser: CommandLineParser = new DefaultParser()

    try {
      // 解析命令行参数
      val cmd = parser.parse(options, args)

      // 检查是否包含帮助选项
      if (cmd.hasOption("h")) {
        printHelp(options)
      } else {
        // 获取文件路径选项的值
        val filePath = cmd.getOptionValue("f")
        println(s"指定的文件路径是:$filePath")
      }
    } catch {
      case e: ParseException =>
        println(s"解析命令行参数时发生错误:${e.getMessage}")
        printHelp(options)
    }
  }

  // 显示帮助信息
  def printHelp(options: Options): Unit = {
    val formatter = new HelpFormatter()
    formatter.printHelp("CommandLineParserExample", options)
  }
}
相关推荐
都叫我大帅哥1 分钟前
“让AI修就行”?我劝你收回这句话——来自一位Java博主的硬核反常识
后端
whyfail26 分钟前
前端学 Spring Boot(8):接口为什么越用越慢?
前端·spring boot·后端
麻瓜老宋1 小时前
AI开发C语言应用按步走,表达式计算器calc的第二十三步,多行输入、进制输出、错误恢复、常量折叠、配置加载等
c语言·开发语言·atomcode
q567315231 小时前
企业级 HTTP 代理采购选型:技术评估清单 15 项
开发语言·网络·爬虫·网络协议·http·隧道ip·代理ip
Muscleheng2 小时前
Spring Boot 3.x 集成 DeepSeek 实现 Function Calling(工具调用)
人工智能·spring boot·后端·ai·spring ai·deepseek
@航空母舰2 小时前
SpringBoot通过Map实现天然的策略模式
java·spring boot·后端
天天进步20152 小时前
Python全栈项目--智能办公自动化系统
开发语言·python
IT_陈寒2 小时前
JavaScript的this又双叒叕让我怀疑人生了
前端·人工智能·后端
陈随易2 小时前
MCP协议第5次更新,从打电话到微信聊天的巨大变革
前端·后端·程序员