title: Java - close multi-layer stream wrapper
body: <p>In Java, we usually use a stream object to wrap another stream class for efficiency. For example:</p>
  
  <pre><code>Object obj = new MyClass();
  try {
      FileOutputStream fos = new FileOutputStream("test.txt");
      ObjectOutputStream oos = new ObjectOutputStream(fos);
  
     oos.writeObject(obj);
     oos.flush();
  } catch(IOException e) {
      e.printStackTrace();
  } finally {
      fos.close();
      oos.close();
  }
  </code></pre>
  
  <p>I use <code>ObjectOutputStream</code> to wrap <code>FileOutputStream</code>. A similar case is using <code>BufferedReader</code> to wrap <code>InputStreamReader</code>.</p>
  
  <p>My question is how to close the <code>fos</code> and <code>oos</code> properly in order. Which one should be closed first? Or just need to close either one.
  Usually closing both streams will work, but I feel uncomfortable with this way since I don't understand the semantics. I just use the close method to close everything, while I don't know why not just close <code>fos</code> or <code>oos</code>.</p>