Exemplo n.º 1
0
  /**
   * Converts UTF-16 inputFile to UTF-8 outputFile. Does not overwrite existing outputFile file.
   *
   * @param inputFile UTF-16 file
   * @param outputFile UTF-8 file after conversion
   * @throws IOException
   */
  public static void convertFileFromUtf16ToUtf8(File inputFile, File outputFile)
      throws IOException {
    String charset;
    if (inputFile == null || !inputFile.canRead()) {
      throw new FileNotFoundException("Can't read inputFile.");
    }

    try {
      charset = getFileCharset(inputFile);
    } catch (IOException ex) {
      LOGGER.debug("Exception during charset detection.", ex);
      throw new IllegalArgumentException("Can't confirm inputFile is UTF-16.");
    }

    if (isCharsetUTF16(charset)) {
      if (!outputFile.exists()) {
        BufferedReader reader = null;

        try {
          if (equalsIgnoreCase(charset, CHARSET_UTF_16LE)) {
            reader =
                new BufferedReader(new InputStreamReader(new FileInputStream(inputFile), "UTF-16"));
          } else {
            reader =
                new BufferedReader(
                    new InputStreamReader(new FileInputStream(inputFile), "UTF-16BE"));
          }
        } catch (UnsupportedEncodingException ex) {
          LOGGER.warn("Unsupported exception.", ex);
          throw ex;
        }

        BufferedWriter writer =
            new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8"));
        int c;

        while ((c = reader.read()) != -1) {
          writer.write(c);
        }

        writer.close();
        reader.close();
      }
    } else {
      throw new IllegalArgumentException("File is not UTF-16");
    }
  }