“close” a Stream?

2019-02-22 15:20发布

问题:

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

回答1:

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


标签: scala io stream