Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Input/OutputStreams close on destruction?

Tags:

java

scope

Does InputStreams and OutputStreams in Java close() on destruction? I fully understand that this may be bad form (esp in C and C++ world), but I'm curious.

Also, suppose I have the following code:

private void foo()
{
    final string file = "bar.txt";
    Properties p = new Properties();
    p.load( new FileInputStream(file) );
    //...
}

Does the nameless FileInputStream goes out of scope after p.load(), and therefore get destroyed, kinda like C++ scoping rules? I tried searching for anonymous variable scope for java on Google, but that didn't turn up what I thought it would be.

Thanks.

like image 583
Calyth Avatar asked Oct 05 '09 21:10

Calyth


1 Answers

First answer: there's no such thing as "destruction" (in the C++ sense) in Java. There's only the Garbage Collector, which may or may not wake up and do its job when it sees an object that's ready to be collected. GC in Java is generally untrustworthy.

Second answer: sometimes yes, sometimes no, but not worth taking a risk over. From Elliote Rusty Harold's Java IO:

Not all streams need to be closed—byte array output streams do not need to be closed, for example. However, streams associated with files and network connections should always be closed when you're done with them. For example, if you open a file for writing and neglect to close it when you're through, then other processes may be blocked from reading or writing to that file.

According to Harold, the same goes for Input or Output streams. There are some exceptions (he notes System.in), but in general, you're taking a risk if you don't close file streams when you're done. And close them in a finally block, to make sure they get closed even if an exception is thrown.

like image 171
rtperson Avatar answered Oct 09 '22 16:10

rtperson