Do we always have to close the stream?
Have a FileInputStream, I am wondering whether I need to close it or not? If yes,开发者_如何转开发 if I pass this stream object to the other method, can I close in that sub method?
Yes, you can close the stream in the method where you passed it.
But beware. If you use the same stream after the method call it will remain closed.
The best practice is to close the stream after you've done all you wanted with it.
YES - If you are sure that nothing more will be written to the stream.
NO - e.g. using outputStream in Servlet - you get this stream, write to them but you don't close it. This is because something later can have access to the same stream. The main rule is: Always close streams which you open by yourself
Yes you you should close it and you can close it if you pass it into a submethod. If you pass it into a Reader though, if you call close on the Reader it will also close the stream.
You can close the stream anywhere you want. But you should close the stream where you opened it for better readability. You can still process the stream in an other method:
try {
InputStream stream = //open the stream;
PerformActionOnStream(s);
} catch (IOException e) {
//handle error
} finally {
stream.close();
}
There is no reason to close the stream in PerformActionOnStream()
. Just return when you are done.
In java 7
is better to simply
try(InputStream stream = new MyStream()) {
// code
} catch (Exception e) {
//
}
You should always close a stream in order to free open resources on your OS. Opening a stream always returns an identifier which you can use to close it wherever you are in your code (as long as the identifier is valid), whether their from another method or class.
精彩评论