Should I close Streams created with java.nio.file.Files.newInputStream?
Asked Answered
B

2

6

In the stream tutorial, nothing is said about closing streams gained from Files.newInputStream( path ). Only some obscure:

Whether the returned stream is asynchronously closeable and/or interruptible is highly file system provider specific and therefore not specified.

What is "asyncronously" in this context? If I close the stream explicitly or if another thread closes the stream asyncronously?

Brabble answered 20/1, 2015 at 14:52 Comment(1)
Left unclosed, it seems to keep a file descriptor occupied per file provided by the stream... which is really not what you may want dealing with large directories.Shanonshanta
O
5

You definitely must close the obtained InputStream, just like all others. The term "asynchronously closeable" refers to the ability to close the stream while another thread is blocked on an I/O operation on it.

From InterruptibleChannel documentation:

A channel that implements this interface is asynchronously closeable: If a thread is blocked in an I/O operation on an interruptible channel then another thread may invoke the channel's close method. This will cause the blocked thread to receive an AsynchronousCloseException.

Olivaolivaceous answered 20/1, 2015 at 15:0 Comment(4)
So the authors of the tutorial just forgot about closing the streams? docs.oracle.com/javase/tutorial/essential/io/…Brabble
No. They use the proper Automatic Resource Management idiom.Olivaolivaceous
That is what I want to know, what is this Idiom where is it described? Is the destructor closing the stream? I seem to have overlooked an essential part.Brabble
Found it, here: oracle.com/technetwork/articles/java/… Thank you so much!Brabble
G
2

You can do this conveniently with the new try with resources option.

try(/*initialize resources here*/)
{
}

They will automatically be closed after the try block. Add a catch as necessary.

Gawk answered 5/10, 2018 at 17:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.