-
Notifications
You must be signed in to change notification settings - Fork 141
Streams
Rajesh R edited this page Jun 16, 2024
·
1 revision
Various ways to slurp a file without loading its contents into memory:
val bytes : Iterator[Byte] = file.bytes()
val chars : Iterator[Char] = file.chars()
val lines : Iterator[String] = file.lineIterator() //file.lines loads all lines in memory
Note: The above APIs can be traversed at most once e.g. file.bytes
is a Iterator[Byte]
which only allows TraversableOnce
.
To traverse it multiple times without creating a new iterator instance, convert it into some other collection e.g. file.bytes.toStream
You can write an Iterator[Byte]
or an Iterator[String]
back to a file:
file.writeBytes(bytes)
file.printLines(lines)
tee
multiple outputstreams:
val s3 = s1 tee s2
s3.printWriter.println(s"Hello world") // gets written to both s1 and s2