Erix
Erix

Reputation: 7105

How do I create a Sink to read all bytes from the Source?

I have a scala method that takes this source as per my requirements

def func(data : Source[ByteString,Any]) { ... }

all I want to do, for now, is to read all of the bytes from this source and write them to a file. I've read a lot of examples that do more complex things like fold a calculation over all values. I want something more simple that just gets the bytes in order so I can write them out. How would I do this?

Upvotes: 1

Views: 815

Answers (2)

fcat
fcat

Reputation: 1251

I want to contribute @Dylan's answer by giving an example:

def func(src : Source[ByteString,Any], filePath:String) {  
  val sink: Sink[ByteString, Future[IOResult]] = FileIO.toPath(Paths.get(props.path))
  src.runWith(sink)
}

Upvotes: 1

Dylan
Dylan

Reputation: 13922

I think FileIO.toFile should work.

It creates a Sink that takes the incoming bytes and writes them to a file.

Note that since you are using streams, you should avoid thinking in terms of "getting all of the data" in order to send it somewhere. Instead, you should think of "what do I do with this chunk of data that I got". If, for example, your data source's sized numbered in the gigabytes, trying to collect all of the data in one place would almost certainly cause an OutOfMemoryError.

Upvotes: 4

Related Questions