Search code examples
javartffileutils

org.apache.commons.io.FileUtils - change text encodig


I have one file which contains text(ukranian symbols). Example: ${name} - привіт. I need to replace from ${name} to Саша. But in output file I recive something like this: пÑ??Ð¸Ð²ÐµÑ - привіт instead of Саша- привіт. But if I use .txt instead .rtf - all is fine. I understand the problem in the coding but can't solve it.

Code example:

File file = new File("original.rtf");
String content = FileUtils.readFileToString(file);

content = content.replace("${name}", "Саша");

File fileNew = new File("changed.rtf");
FileOutputStream fop = new FileOutputStream(fileNew);

byte[] contentInBytes = content.getBytes("UTF-8");
fop.write(contentInBytes);
fop.flush();
fop.close();

Solution

  • http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#readFileToString%28java.io.File%29

    Deprecated. 2.5 use readFileToString(File, Charset) instead

    Also, make sure that the java compiler is reading your Java source with the same encoding as it is stored in (UTF-8 recommended), with the -encoding switch.