Java 如何让 PrintWriter 写成 UTF-8?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21096367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make the PrintWriter to write UTF-8?
提问by yeah its me
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
回答by Njol
Use an OutputStreamWriter
:
使用OutputStreamWriter
:
pstream = new PrintWriter(new OutputStreamWriter(
csocket.getOutputStream(), StandardCharsets.UTF_8), true)
回答by Daniil
Look at Java: Difference between PrintStream and PrintWriterdiscussion.
查看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 参数或方法(请参阅第二个答案)。
回答by Error
回答by 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);
}
回答by dave110022
Don't user PrintWriter. If you need UTF-8 encoding, just write direct to the OutputStream.
不要使用 PrintWriter。如果需要UTF-8编码,直接写入OutputStream即可。
csocket.getOutputStream().write(res.getBytes("UTF-8"));
回答by Krzysztof
OutputStream os = new FileOutputStream("file.txt");
PrintWriter pw = new PrintWriter(new OutputStreamWriter(os, "UTF-8"));