How to make the PrintWriter to write UTF-8?

送分小仙女□ 提交于 2019-12-02 21:41:56
Njol

Use an OutputStreamWriter:

pstream = new PrintWriter(new OutputStreamWriter(
    csocket.getOutputStream(), StandardCharsets.UTF_8), true)
Daniil

Look at Java: Difference between PrintStream and PrintWriter discussion.

To be quick: you can use -Dfile.encoding=utf8 JVM parameter or method suggested in the discussion (see second answer).

dave110022

Don't user PrintWriter. If you need UTF-8 encoding, just write direct to the OutputStream.

csocket.getOutputStream().write(res.getBytes("UTF-8"));
Shahab Saalami
PrintWriter out1 = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    out1 = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8),true);
} else { 
    out1 = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8"), true);
}

you can only write to file with any charset, otherwise platform default charset used see doc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!