You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala执行resources目录下sh文件时遭遇IOException问题排查

问题分析与解决办法

错误原因

  • 相对路径指向错误:你代码里的./hiveCommand.sh是基于程序运行时的当前工作目录,而非项目的src/main/resources目录,两者路径不匹配,导致系统找不到文件。
  • 资源文件的特殊性:当项目打包为jar包后,hiveCommand.sh会被嵌入jar内部,并非文件系统中的独立文件,直接用文件路径调用系统命令无法访问。

解决方案

场景1:本地开发环境运行

  • 使用绝对路径:直接填写hiveCommand.sh在本地的完整绝对路径,示例代码:
    import sys.process._
    "/Users/your-name/your-project/src/main/resources/hiveCommand.sh" !!
    
  • 调整工作目录:在IDE的运行配置中,将程序的工作目录设置为src/main/resources,此时./hiveCommand.sh就能正确指向目标文件。

场景2:打包后生产环境运行

由于jar包内的资源无法直接作为可执行文件调用,需先将资源提取到临时目录再执行:

import sys.process._
import java.io.{File, FileOutputStream}

// 读取jar内的资源文件
val resourceStream = getClass.getResourceAsStream("/hiveCommand.sh")
if (resourceStream == null) throw new RuntimeException("资源文件hiveCommand.sh不存在")

// 创建临时可执行文件
val tempShFile = File.createTempFile("hiveCmd", ".sh")
tempShFile.setExecutable(true)

// 将资源内容写入临时文件
val outputStream = new FileOutputStream(tempShFile)
resourceStream.transferTo(outputStream)
resourceStream.close()
outputStream.close()

// 执行脚本并清理临时文件
try {
  tempShFile.getAbsolutePath !!
} finally {
  tempShFile.deleteOnExit()
}

内容的提问来源于stack exchange,提问作者Jelly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 18:50:31