title: Closing streams/sockets and try-catch-finally
body: <p>Here is an example I have questions about (it comes from another SO question):</p>
  
  <pre><code>public static void writeToFile (final String filename)
  {
      PrintWriter out = null;     
      FileOutputStream fos = null;
  
      try
      {
          fos = new FileOutputStream(filename);
          out = new PrintWriter(new BufferedWriter(
                                new OutputStreamWriter(fos, "UTF-8")));
  
          for (final String line : log)
          {
              out.println(line);
          }
  
          out.flush();
          out.close();
      }
      catch (final Exception e)
      {
          System.err.println("Unable to write log to file.");
      }
      finally
      {
          if (fos != null)
          {
              try
              {
                  fos.close();
              }
              catch (final IOException e)
              {
                  System.err.println("Unable to write log to file.");
              }
          }
      }
  }
  </code></pre>
  
  <p>Now I think this code works fine and releases all the resources where it should etc. My questions are:</p>
  
  <ol>
  <li><p>Why should I be closing the <code>FileOutputStream</code> in the <code>finally</code> section of the <code>try-catch-finally</code>? Surely I could just put the code sequentially after the <code>try-catch</code>?</p></li>
  <li><p>Why must I close the <code>FileOutputStream</code> separately rather than simply replacing <code>new OutputStreamWriter(fos, ...</code> with <code>new OutputStreamWriter(new FileOutputStream(filename), ...</code>?  If I close the FileOutputStream first, will that automatically close the rest and release the resources?  Same questions apply for sockets, if I close a socket connection does that automatically close the stream readers/writers and release the resources?</p></li>
  <li><p>I've been told repeatedly to ensure that I read and write streams with "UTF-8" due to different systems having different charsets (or something along those lines).  Is this still applicable when reading/writing RAW byte data (say from a non-text file, or the result of an encryption) as I thought charsets where to do with textual characters only?</p></li>
  </ol>