在Scala中,给定一个二进制文件,我对检索Array [Byte]项的 list 感兴趣。
例如,二进制文件包含由字符/字节“ my-delimiter”定界的项目。
如何获取每个项目的Array [Byte]列表?
答案 0 :(得分:0)
功能解决方案,借助java.nio
:
import java.nio.file.{Files, Paths}
object Main {
private val delimiter = '\n'.toByte
def main(args: Array[String]): Unit = {
val byteArray = Files.readAllBytes(Paths.get(args(0)))
case class Accumulator(result: List[List[Byte]], current: List[Byte])
val items: List[Array[Byte]] = byteArray.foldLeft(Accumulator(Nil, Nil)) {
case (Accumulator(result, current), nextByte) =>
if (nextByte == delimiter)
Accumulator(current :: result, Nil)
else
Accumulator(result, nextByte :: current)
} match {
case Accumulator(result, current) => (current :: result).reverse.map(_.reverse.toArray)
}
items.foreach(item => println(new String(item)))
}
}
但是,该解决方案的性能预期较差。这对您有多重要?您将读取多少个文件,大小和读取频率?如果性能很重要,那么您应该使用输入流和可变集合:
import java.io.{BufferedInputStream, FileInputStream}
import scala.collection.mutable.ArrayBuffer
object Main {
private val delimiter = '\n'.toByte
def main(args: Array[String]): Unit = {
val items = ArrayBuffer.empty[Array[Byte]]
val item = ArrayBuffer.empty[Byte]
val bis = new BufferedInputStream(new FileInputStream(args(0)))
var nextByte: Int = -1
while ( { nextByte = bis.read(); nextByte } != -1) {
if (nextByte == delimiter) {
items.append(item.toArray)
item.clear()
} else {
item.append(nextByte.toByte)
}
}
items.append(item.toArray)
items.foreach(item => println(new String(item)))
bis.close()
}
}