0

In my finally clause I clean up any streams, e.g.,

            finally // Clean up 
            {
                if (os != null) {
                    try {
                        os.close();
                    }
                    catch (IOException ioe) {
                        logger.warn("Failed to close outputStream", ioe);
                    }
                }
                if (is != null) {
                    try {
                        is.close();
                    }
                    catch (IOException ioe) {
                        logger.warn("Failed to close inputStream", ioe);
                    }
                }

But I see that the Streams remain non-NULL even after closing. So is it wrong to check for NULL? Or do I not see the result of close ?

gene b.
  • 10,512
  • 21
  • 115
  • 227
  • Are you using Java 7? if so, look at try-with-resources, then you don't even have to worry about closing the streams as it will be handled for you (as long as they implement autoclosable, which most things like BufferedInputStream do – Ash Oct 07 '16 at 14:21

1 Answers1

5

The stream "object" is a reference to a instance of a stream. Whether the stream is open or not is part of its state. The close function is a function that runs in the objects state and thus will not affect references to it.

The reference will stay non-NULL until you set it null, but the stream's state is closed meaning that you cant use it anymore.

Flying Dutch Boy
  • 344
  • 3
  • 17
  • 1
    Is there a way to check if it's closed? And should that be used as the criterion? – gene b. Oct 07 '16 at 14:23
  • 2
    @geneb. According to these posts: http://stackoverflow.com/questions/8655901/how-to-check-whether-an-outputstream-is-closed and http://stackoverflow.com/questions/981196/how-to-know-if-a-bufferedreader-stream-is-closed you will not be able to see... But the close function will never throw an exception. You could say: "os=null; is=null" after the closing to make the references null. But if the function finishes after the closing it is not needed. Your code is good as it is ;) – Flying Dutch Boy Oct 07 '16 at 14:29