简体   繁体   English

如何让 PrintWriter 写成 UTF-8?

[英]How to make the PrintWriter to write UTF-8?

How to make the PrintWriter to write UTF-8?如何让PrintWriter写成 UTF-8?

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

Use an OutputStreamWriter :使用OutputStreamWriter

pstream = new PrintWriter(new OutputStreamWriter(
    csocket.getOutputStream(), StandardCharsets.UTF_8), true)
OutputStream os = new FileOutputStream("file.txt");
PrintWriter pw = new PrintWriter(new OutputStreamWriter(os, "UTF-8"));

Look at Java: Difference between PrintStream and PrintWriter discussion.看看Java:PrintStream 和 PrintWriter 之间的区别讨论。

To be quick: you can use -Dfile.encoding=utf8 JVM parameter or method suggested in the discussion (see second answer).快速:您可以使用讨论中建议的 -Dfile.encoding=utf8 JVM 参数或方法(请参阅第二个答案)。

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);
}

Don't user PrintWriter.不要使用 PrintWriter。 If you need UTF-8 encoding, just write direct to the OutputStream.如果您需要 UTF-8 编码,只需直接写入 OutputStream。

csocket.getOutputStream().write(res.getBytes("UTF-8"));

您只能使用任何字符集写入文件,否则使用平台默认字符集,请参阅文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM