scala解析命令行参数
如何用scala解析命令行参数:
首先,需要在项目中添加Apache Commons CLI库的依赖。可以在build.sbt
文件中添加如下行:
libraryDependencies += "commons-cli" % "commons-cli" % "1.4"
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)}
}