title: Java file encoding conversion from ANSI to UTF8
body: <p>I have a requirement to change the encoding of a file from ANSI(windows-1252) to UTF8. I wrote below program to do it through java. This program converts the characters to UTF8, but when I opened the file in notepad++ the encoding type was displayed as ANSI as UTF8. This gives me error when I import this file in access db. A file with UTF8 encoding only is desired. Also the requirement is to convert the file without opening it in any editor.</p>
  
  <pre><code>public class ConvertFromAnsiToUtf8 {
  
      private static final char BYTE_ORDER_MARK = '\uFEFF';
      private static final String ANSI_CODE = "windows-1252";
      private static final String UTF_CODE = "UTF8";
      private static final Charset ANSI_CHARSET = Charset.forName(ANSI_CODE);
  
      public static void main(String[] args) {
  
          List&lt;File&gt; fileList;
          File inputFolder = new File(args[0]);
          if (!inputFolder.isDirectory()) {
              return;
          }
          File parentDir = new File(inputFolder.getParent() + "\\"
                      + inputFolder.getName() + "_converted");
  
          if (parentDir.exists()) {
              return;
          }
          if (parentDir.mkdir()) {
  
          } else {
              return;
          }
  
          fileList = new ArrayList&lt;File&gt;();
          for (final File fileEntry : inputFolder.listFiles()) {
              fileList.add(fileEntry);
          }
  
          InputStream in;
  
          Reader reader = null;
          Writer writer = null;
          try {
              for (File file : fileList) {
                  in = new FileInputStream(file.getAbsoluteFile());
                  reader = new InputStreamReader(in, ANSI_CHARSET);
  
                  OutputStream out = new FileOutputStream(
                              parentDir.getAbsoluteFile() + "\\"
                                              + file.getName());
                  writer = new OutputStreamWriter(out, UTF_CODE);
                  writer.write(BYTE_ORDER_MARK);
                  char[] buffer = new char[10];
                  int read;
                  while ((read = reader.read(buffer)) != -1) {
                      System.out.println(read);
                      writer.write(buffer, 0, read);
                  }
              }
              reader.close();
              writer.close();
          } catch (FileNotFoundException e) {
              e.printStackTrace();
          } catch (UnsupportedEncodingException e) {
              e.printStackTrace();
          } catch (IOException e) {
              e.printStackTrace();
          }
      }
  }
  </code></pre>
  
  <p>Any pointers will be helpful. </p>
  
  <p>Thanks,
  Ashish</p>