title: How to read a file in Java with specific character encoding?
body: <p>I am trying to read a file in as either UTF-8 or Windows-1252 depending on the output of this method:</p>
  
  <pre><code>public Charset getCorrectCharsetToApply() {
      // Returns a Charset for either UTF-8 or Windows-1252.
  }
  </code></pre>
  
  <p>So far, I have:</p>
  
  <pre><code>String fileName = getFileNameToReadFromUserInput();
  InputStream is = new ByteArrayInputStream(fileName.getBytes());
  InputStreamReader isr = new InputStreamReader(is, getCorrectCharsetToApply());
  BufferedReader buffReader = new BufferedReader(isr);
  </code></pre>
  
  <p>The problem I'm having is converting the <code>BufferedReader</code> instance to a <code>FileReader</code>.</p>
  
  <p>Furthermore:</p>
  
  <ul>
  <li>The name of the file itself (<code>fileName</code>) cannot be trusted to be a particular <code>Charset</code>; sometime the file name will contain UTF-8 characters, and sometimes Windows-1252. Same goes for the file's content (however if file name and file content will <em>always</em> have matching charsets).</li>
  <li>Only the logic inside <code>getCorrectCharsetToApply()</code> can select the charset to apply, so attempting to read a file by its name <em>prior</em> to calling this method could very well result with, Java trying to read the file name with the wrong encoding...which causes it to die!</li>
  </ul>
  
  <p>Thanks in advance!</p>