Why stream from BufferedReader::lines is not closing the reader?
Alan Bateman
Alan.Bateman at oracle.com
Mon Nov 18 10:10:16 UTC 2013
On 18/11/2013 08:46, Tomasz Kowalczewski wrote:
> 3. If I want the stream to be closed I need to do:
>
> reader.lines().onClose(is::close).doStreamyStuff().collect(...);
>
> where *is* is an underlying InputStream.
>
> The problem with this code is that ::close throws IOException which is not
> compatible with Runnable accepted by onClose(); Is there a better way? Some
> wrapper I can use to inject a call to close?
>
As you have a reference to the buffered reader it might be simplest to
use try-with-resources so that the reader (and hence the underlying
input stream) will be closed, something like:
try (BufferReader reader = ...) {
reader.lines().doStreamyStuff().collect(...);
}
Alternatively, if the reader is to a file then you can use Files.lines
as it returns a Stream that will arrange to close the underlying file
when you close the stream.
Otherwise if you really need to really want the stream close to close
the underlying input stream (or reader more likely) then the runnable
will need to translate the checked IOException to an unchecked
exception. The new java.io.UncheckedIOException is probably what you want.
-Alan.
More information about the core-libs-dev
mailing list