1

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.

3
  • What is a byte string? Do you mean a String or a byte array? Commented Nov 9, 2015 at 20:55
  • Possible duplicate of How to read a file as a byte array in Scala Commented Nov 9, 2015 at 20:55
  • @Daenyth OP is referring to akka.util.ByteString Commented Nov 9, 2015 at 21:06

2 Answers 2

6

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
Sign up to request clarification or add additional context in comments.

Comments

3

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

val source = FileIO.fromPath(filename)

1 Comment

Worked as charm for HttpEntity, when I'm posting a file using akka-http. Thank you!\

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.