How to write a UTF-8 file with Java?

ID : 20211

viewed : 25

Tags : javafile-ioutf-8java

Top 5 Answer for How to write a UTF-8 file with Java?

vote vote

92

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 } 
vote vote

84

Try this

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

78

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.

vote vote

68

Since Java 7 you can do the same with Files.newBufferedWriter a little more succinctly:

Path logFile = Paths.get("/tmp/example.txt"); try (BufferedWriter writer = Files.newBufferedWriter(logFile, StandardCharsets.UTF_8)) {     writer.write("Hello World!");     // ... } 
vote vote

53

All of the answers given here wont work since java's UTF-8 writing is bugged.

http://tripoverit.blogspot.com/2007/04/javas-utf-8-and-unicode-writing-is.html

Top 3 video Explaining How to write a UTF-8 file with Java?

Related QUESTION?