How to make the PrintWriter to write UTF-8?

2019-03-11 15:15发布

How to make the PrintWriter to write UTF-8?

pstream = new PrintWriter(csocket.getOutputStream(), true);
String res = "some string";
pstream.println(res); // here I want to output string as UTF-8

5条回答
霸刀☆藐视天下
2楼-- · 2019-03-11 15:21

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

查看更多
对你真心纯属浪费
3楼-- · 2019-03-11 15:35

Use an OutputStreamWriter:

pstream = new PrintWriter(new OutputStreamWriter(
    csocket.getOutputStream(), StandardCharsets.UTF_8), true)
查看更多
做自己的国王
4楼-- · 2019-03-11 15:41

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

csocket.getOutputStream().write(res.getBytes("UTF-8"));
查看更多
萌系小妹纸
5楼-- · 2019-03-11 15:43
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);
}
查看更多
ら.Afraid
6楼-- · 2019-03-11 15:47

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).

查看更多
登录 后发表回答