I am reading text from a java BufferedReader
like this:
Stream.continually(reader.readLine).takeWhile {
case null => reader.close; false
case _ => true
}
This works, but just seems a little clumsy to me. I wish there was something like .whenDone
on Stream
, so that I could tell it to close the reader after the whole thing is consumed, and then just do .takeWhile(_ != null)
.
Is there some way to do that I don't know about? Or, perhaps, a better way to get a stream of lines from a java Reader
(if it was an InputStream
, I could just do Source.fromInputStream
for example, but there does not seem to be an equivalent for Reader
... note, that this would only partially solve the problem though, because one might want to do the same thing with other "closable" objects - a ResultSet
for example)?
You can get the .whenDone
behaviour by appending another Stream
.
This makes the code a bit more expressive and could also be used in other cases. It is something but I guess far from perfect.
def closeStream: Stream[Nothing] = {
reader.close
Stream.Empty
}
Stream.continually(reader.readLine).takeWhile(_ != null) #::: closeStream
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With