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();
}
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!");
// ...
}
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.