简体   繁体   English

如何在scala中以字节串的形式读取文件?

[英]how to read a file as a bytestring in a scala?

I want to make TCP-IO in scala. 我想在scala中制作TCP-IO。 And the data type will be bytestring. 并且数据类型将为字节串。 Then, I want to read a file as a bytestring type in a scala, intellij, akka 2.3.14. 然后,我想在scala intellij,akka 2.3.14中读取一个字节类型的文件。

Assuming you're talking about akka.util.ByteString you could make 1 ByteString for the entire file: 假设您正在谈论akka.util.ByteString ,则可以为整个文件创建1 ByteString:

import akka.util.ByteString
import scala.io.Source

def fileToByteStr(filename : String) : ByteString = 
  ByteString(Source.fromFile(filename).mkString)

Or, if you want 1 ByteString for each line in your file which lazily remains "on the plate" until the Iterator is drained: 或者,如果您要为文件中的每一行使用1个ByteString,而这些行会懒惰地保留在“板上”,直到耗尽Iterator:

def fileToMultipleByteStr(filename : String) : Iterator[ByteString] = 
  Source.fromFile(filename)
        .getLines()
        .map(ByteString.apply)

If you want the data in memory you can drain the Iterator to a Seq: 如果要将数据存储在内存中,可以将迭代器消耗到Seq:

val memoryHog = fileToMultipleByteStr("foo.txt").toSeq

如果要获取Akka流的Source[ByteString, _] ,我建议:

val source = FileIO.fromPath(filename)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM