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

Scala中如何将fromResource获取的BufferedSource转为InputStream?

在Scala中将BufferedSource转换为InputStream的方法

直接通过BufferedSource获取InputStream

scala.io.Source.fromResource返回的BufferedSource类自带inputStream属性,直接调用就能得到对应的InputStream,示例代码如下:

// 从类路径读取资源得到BufferedSource
val source = scala.io.Source.fromResource("keystore.jks")
// 转换为InputStream
val inputStream = source.inputStream

// 使用完毕务必关闭资源,避免内存泄漏
try {
  // 调用需要InputStream参数的Java方法
  targetJavaMethod(inputStream)
} finally {
  source.close() // 关闭source会同时关闭其内部的InputStream,无需重复关闭
}

更高效的方式:跳过Source直接获取InputStream

如果不需要BufferedSource的文本处理能力,也可以直接通过类加载器获取InputStream,省去转换步骤:

val inputStream = getClass.getClassLoader.getResourceAsStream("keystore.jks")

try {
  inputStream match {
    case null => throw new IllegalArgumentException("类路径中未找到keystore.jks资源")
    case _ => targetJavaMethod(inputStream)
  }
} finally {
  if (inputStream != null) inputStream.close()
}

自动管理资源(Scala 2.13+)

Scala 2.13及以上版本可以用Using语句自动处理资源关闭,简化代码:

import scala.util.Using

Using(scala.io.Source.fromResource("keystore.jks").inputStream) { inputStream =>
  targetJavaMethod(inputStream)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 23:47:38