How to write a UTF-8 file with Java?

mark smith picture mark smith · Jun 16, 2009 · Viewed 368.5k times · Source

I have some current code and the problem is its creating a 1252 codepage file, i want to force it to create a UTF-8 file

Can anyone help me with this code, as i say it currently works... but i need to force the save on utf.. can i pass a parameter or something??

this is what i have, any help really appreciated

var out = new java.io.FileWriter( new java.io.File( path )),
        text = new java.lang.String( src || "" );
    out.write( text, 0, text.length() );
    out.flush();
    out.close();

Answer

skaffman picture skaffman · Jun 16, 2009

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
}