Hi all I understand that if we read bytes from an InputStream and we have finished reading all the bytes (or we do not intend to read to the end of stream), we must call close() to release system resources associated with the stream.
Now I was wondering if I read bytes and it throws a java.io.IOException, am I still required to call close() to release system resources associated with the stream?
Or is it true that on errors, streams are closed automatically so we do not have to call close() ?
The OS itself might close the streams and deallocate resources because the process (namely, the JVM) terminates, but it is not mandated to do so.
You should always implement a
finallyblock where you close it in cases like these, e.g. like this:This isn’t really guaranteed to work if it threw in the first place, but you’ll probably wanna terminate at that point anyway since your data source is probably messed up in some way. You can find out more info about it if you keep the
InputStream‘s provider around, like, if I kept a ref to theFileobject around in my example, I could check whether it exists etc viaFile‘s interface, but that’s specific to your particular data provider.This tactic gets more useful with network sessions that throw, e.g., with Hibernate…