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

如何从scala.io.BufferedSource获取原始Array[Byte]?

解决方案

最简单的实现方式是利用BufferedSource的mkString方法获取完整原始内容(会保留所有换行符及其他原始字符),再结合其自身的编码信息转换为字节数组:

import scala.io.Source

// 假设你已持有bufferedSource实例
val bufferedSource: Source = Source.fromFile("example.txt")
try {
  // 获取包含所有原始字符的完整内容字符串
  val rawContent = bufferedSource.mkString
  // 按Source指定的编码转换为字节数组
  val rawBytes = rawContent.getBytes(bufferedSource.encoding)
} finally {
  // 务必关闭资源,避免泄漏
  bufferedSource.close()
}

如果处理大文件,不想把全部内容加载到内存,可以直接操作底层输入流读取字节:

import scala.io.Source
import java.io.{ByteArrayOutputStream, InputStream}

val bufferedSource: Source = Source.fromFile("example.txt")
try {
  val inputStream: InputStream = bufferedSource.inputStream
  val baos = new ByteArrayOutputStream()
  val buffer = new Array[Byte](8192)
  var bytesRead = 0
  while ({ bytesRead = inputStream.read(buffer); bytesRead != -1 }) {
    baos.write(buffer, 0, bytesRead)
  }
  val rawBytes = baos.toByteArray
} finally {
  bufferedSource.close()
}

关键说明

  • mkString会读取Source的全部内容,不会像getLines那样忽略换行分隔符,完全保留原始字符结构。
  • 必须使用bufferedSource.encoding指定编码,确保字节转换的正确性(Source创建时已绑定编码,默认是平台编码)。
  • 无论哪种方式,都要在finally块中关闭BufferedSource,避免资源泄漏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 15:00:49