Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are streams closed automatically on error?

Tags:

java

io

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() ?

like image 852
Pacerier Avatar asked Jan 20 '12 13:01

Pacerier


People also ask

What is stream closed error?

CAUSE. After the first time the stream is read the runtime will close it. Note that is not the contents of the stream that are being passed when assigning it but the reference to the stream. It is a programming error to assume otherwise.

What happens if you forget to close your output stream before your program ends?

In extreme cases, the program could exhaust the resources available to it (e.g. number of simultaneously open files). Additionally, for output, data you have written to such sinks may remain buffered internally instead of actually being pushed out to the intended destination.

Why do we need to close streams?

yes you need to close stream because, the stream is already full with content and when you close the stream then you can use it again. also data is flush in drive when use flush method. when you close the stream JVM will see that stream is not can be use for further operation.

Where do streams terminate?

The top end of a stream, where its flow begins, is its source. The bottom end is its mouth. In between, the stream flows through its main course or trunk.


1 Answers

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 finally block where you close it in cases like these, e.g. like this:

InputStream is = null;

try {
    is = new FileInputStream(new File("lolwtf"));
    //read stuff here
} catch (IOException e) {
    System.out.println("omfg, it didn't work");
} finally {
    is.close();
}

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 the File object around in my example, I could check whether it exists etc via File'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...

like image 76
9 revs Avatar answered Sep 28 '22 00:09

9 revs