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)
  }
}
相关推荐
Victor35619 分钟前
MongoDB(28)什么是地理空间索引?
后端
Victor35622 分钟前
MongoDB(29)如何创建索引?
后端
皮皮林5511 小时前
面试官:什么是 fail-fast?什么是 fail-safe?
后端
陈随易2 小时前
前端大咖mizchi不满Rust、TypeScript却爱上MoonBit
前端·后端·程序员
雨中飘荡的记忆3 小时前
Multi-Agent + Skills + Spring AI 构建自主决策智能体
后端·spring
我叫黑大帅4 小时前
Go 语言并发编程的 “工具箱”
后端·面试·go
用户8356290780515 小时前
Python 实现 PowerPoint 形状动画设置
后端·python
用户908324602735 小时前
Spring Boot 缓存架构:一行配置切换 Caffeine 与 Redis,透明支持多租户隔离
后端
tyung5 小时前
zhenyi-base 开源 | Go 高性能基础库:TCP 77万 QPS,无锁队列 16ns/op
后端·go