Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"close" a Stream?

Tags:

io

stream

scala

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)?

like image 542
Dima Avatar asked Nov 08 '22 19:11

Dima


1 Answers

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
like image 62
Pim Verkerk Avatar answered Nov 14 '22 21:11

Pim Verkerk