How to write a UTF-8 file with Java? How to write a UTF-8 file with Java? java java

How to write a UTF-8 file with Java?


Instead of using FileWriter, create a FileOutputStream. You can then wrap this in an OutputStreamWriter, which allows you to pass an encoding in the constructor. Then you can write your data to that inside a try-with-resources Statement:

try (OutputStreamWriter writer =             new OutputStreamWriter(new FileOutputStream(PROPERTIES_FILE), StandardCharsets.UTF_8))    // do stuff}


Try this

Writer out = new BufferedWriter(new OutputStreamWriter(    new FileOutputStream("outfilename"), "UTF-8"));try {    out.write(aString);} finally {    out.close();}


Try using FileUtils.write from Apache Commons.

You should be able to do something like:

File f = new File("output.txt"); FileUtils.writeStringToFile(f, document.outerHtml(), "UTF-8");

This will create the file if it does not exist.