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.
Asked
Active
Viewed 4,213 times
1
-
What is a byte string? Do you mean a String or a byte array? – Daenyth Nov 09 '15 at 20:55
-
Possible duplicate of [How to read a file as a byte array in Scala](http://stackoverflow.com/questions/7598135/how-to-read-a-file-as-a-byte-array-in-scala) – Daenyth Nov 09 '15 at 20:55
-
@Daenyth OP is referring to [akka.util.ByteString](http://doc.akka.io/api/akka/2.3.6/#akka.util.ByteString) – Dylan Nov 09 '15 at 21:06
2 Answers
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

Ramón J Romero y Vigil
- 17,373
- 7
- 77
- 125
3
If you want to get Source[ByteString, _]
for Akka Streams, I'd recommend:
val source = FileIO.fromPath(filename)

Mitrakov Artem
- 1,355
- 2
- 14
- 22
-
Worked as charm for `HttpEntity`, when I'm posting a file using akka-http. Thank you!\ – user40171 Feb 07 '19 at 12:27