title: Is it necessary to call close() in a finally when writing files in Java?
body: <p>There are a few <a href="https://stackoverflow.com/a/4530294/476074">examples</a> where people call <code>close()</code> in their <code>finally</code> block when writing to a file, like this:</p>
  
  <pre><code>OutputStream out = null;
  try {
      out = new FileOutputStream(file);
      out.write(data);
      out.close();
  }
  catch (IOException e) {
      Log.e("Exception", "File write failed: " + e.toString());
  } finally {
      try {
          if (out != null) {
              out.close();
          }
      } catch (IOException e) {
          Log.e("Exception", "File write failed: " + e.toString());
      }
  }
  </code></pre>
  
  <p>But there are <a href="https://stackoverflow.com/questions/9292954/how-to-make-a-copy-of-a-file-in-android">many</a> <a href="https://stackoverflow.com/questions/4178168/how-to-programmatically-move-copy-and-delete-files-and-directories-on-sd">more</a> examples, including <a href="http://developer.android.com/training/basics/data-storage/files.html#WriteInternalStorage" rel="nofollow noreferrer">the official Android docs</a> where they don't do that:</p>
  
  <pre><code>try {
      OutputStream out = new FileOutputStream(file);
      out.write(data);
      out.close();
  }
  catch (IOException e) {
      Log.e("Exception", "File write failed: " + e.toString());
  }
  </code></pre>
  
  <p>Given that the second example is much shorter, is it really necessary to call <code>close()</code> in <code>finally</code> as shown above or is there some mechanism that would clean up the file handle automatically?</p>