开发者社区 问答 正文

在Scala中,如何从字符分隔的二进制文件中读取字节?

"在Scala中,给定一个二进制文件,我想检索Array [Byte]项的列表。

例如,二进制文件具有由字符/字节'my-delimiter'分隔的项目。

如何获取每个项目的数组[字节]列表?"

展开
收起
flink小助手 2018-11-28 15:52:05 1942 分享 版权
1 条回答
写回答
取消 提交回答
  • flink小助手会定期更新直播回顾等资料和文章干货,还整合了大家在钉群提出的有关flink的问题及回答。

    "功能解决方案,帮助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 {

    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()

    }

    }
    private val delimiter = 'n'.toByte"

    2019-07-17 23:16:47
    赞同 展开评论
问答分类:
问答地址: