Ji Won  Choi
Ji Won Choi

Reputation: 31

how to read a file as a bytestring in a scala?

I want to make TCP-IO in scala. 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.

Upvotes: 1

Views: 4416

Answers (2)

Mitrakov Artem
Mitrakov Artem

Reputation: 1523

If you want to get Source[ByteString, _] for Akka Streams, I'd recommend:

val source = FileIO.fromPath(filename)

Upvotes: 3

Assuming you're talking about akka.util.ByteString you could make 1 ByteString for the entire file:

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:

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:

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

Upvotes: 6

Related Questions