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.
-
What is a byte string? Do you mean a String or a byte array?Daenyth– Daenyth2015-11-09 20:55:17 +00:00Commented Nov 9, 2015 at 20:55
-
Possible duplicate of How to read a file as a byte array in ScalaDaenyth– Daenyth2015-11-09 20:55:33 +00:00Commented Nov 9, 2015 at 20:55
-
@Daenyth OP is referring to akka.util.ByteStringDylan– Dylan2015-11-09 21:06:39 +00:00Commented Nov 9, 2015 at 21:06
Add a comment
|
2 Answers
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
Comments
If you want to get Source[ByteString, _] for Akka Streams, I'd recommend:
val source = FileIO.fromPath(filename)
1 Comment
user40171
Worked as charm for
HttpEntity, when I'm posting a file using akka-http. Thank you!\