title: Correct way to close nested streams and writers in Java
body: <p><strong>Note:</strong> This question and most of its answers date to before the release of Java 7. Java 7 provides <a href="https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html" rel="noreferrer">Automatic Resource Management</a> functionality for doing this easilly. If you are using Java 7 or later you should advance to <a href="https://stackoverflow.com/a/21723193">the answer of Ross Johnson</a>.</p>
  
  <hr>
  
  <p>What is considered the best, most comprehensive way to close nested streams in Java? For example, consider the setup:</p>
  
  <pre><code>FileOutputStream fos = new FileOutputStream(...)
  BufferedOS bos = new BufferedOS(fos);
  ObjectOutputStream oos = new ObjectOutputStream(bos);
  </code></pre>
  
  <p>I understand the close operation needs to be insured (probably by using a finally clause). What I wonder about is, is it necessary to explicitly make sure the nested streams are closed, or is it enough to just make sure to close the outer stream (oos)?</p>
  
  <p>One thing I notice, at least dealing with this specific example, is that the inner streams only seem to throw FileNotFoundExceptions. Which would seem to imply that there's not technically a need to worry about closing them if they fail.</p>
  
  <p>Here's what a colleague wrote:</p>
  
  <hr>
  
  <p>Technically, if it were implemented right, closing the outermost
  stream (oos) should be enough. But the implementation seems flawed.</p>
  
  <p>Example:
  BufferedOutputStream inherits close() from FilterOutputStream, which defines it as:</p>
  
  <pre><code> 155       public void close() throws IOException {
   156           try {
   157             flush();
   158           } catch (IOException ignored) {
   159           }
   160           out.close();
   161       }
  </code></pre>
  
  <p>However, if flush() throws a runtime exception for some reason, then
  out.close() will never be called. So it seems "safest" (but ugly) to
  mostly worry about closing FOS, which is keeping the file open.</p>
  
  <hr>
  
  <p>What is considered to be the hands-down best, when-you-absolutely-need-to-be-sure, approach to closing nested streams?</p>
  
  <p>And are there any official Java/Sun docs that deal with this in fine detail?</p>