InputStream in = SomeClass.getInputStream(...);
BufferedInputStream bis = new BufferedInputStream(in);
try {
// read data from bis
} finally {
bis.close();
in.close();
}
The javadoc for BufferedInputStream.close()
doesn't mention whether or not the underlying stream is closed:
Closes this input stream and releases any system resources associated with the stream. Once the stream has been closed, further read(), available(), reset(), or skip() invocations will throw an IOException. Closing a previously closed stream has no effect.
Is the explicit call to in.close()
necessary, or should it be closed by the call to bis.close()
?
DataInputStream is a kind of InputStream to read data directly as primitive data types. BufferedInputStream is a kind of inputStream that reads data from a stream and uses a buffer to optimize speed access to data. data is basicaly read ahead of time and this reduces disk or network access.
Handling inputstream requires OS to use its resources and if you don't free it up once you use it, you will eventually run out of resources.
You do need to close the input Stream, because the stream returned by the method you mention is actually FileInputStream or some other subclass of InputStream that holds a handle for a file. If you do not close this stream you have resource leakage.
A BufferedInputStream adds functionality to another input stream-namely, the ability to buffer the input and to support the mark and reset methods. When the BufferedInputStream is created, an internal buffer array is created.
From the source code of BufferedInputStream :
public void close() throws IOException {
byte[] buffer;
while ( (buffer = buf) != null) {
if (bufUpdater.compareAndSet(this, buffer, null)) {
InputStream input = in;
in = null;
if (input != null)
input.close();
return;
}
// Else retry in case a new buf was CASed in fill()
}
}
So the answer would be : YES
BufferedInputStream doesn't hold any system resources itself; it simply wraps around an InputStream which holds those resources. Therefore the BufferedInputStream forwards the close operation onto the wrapped InputStream which will then release its resources.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With