[英]Best way to write a String to OutputStream in Java
I have an OutputStream
instance which return from HttpURLConnection
. 我有一个从
HttpURLConnection
返回的OutputStream
实例。 I need to write a UTF-8 String into the stream. 我需要将UTF-8字符串写入流中。
I have 2 ways: 我有2种方法:
Use OutputStream
itself 使用
OutputStream
本身
// write String os.write("some utf8 text".getBytes(Charsets.UTF_8));
Use OutputStreamWriter
wrapper 使用
OutputStreamWriter
包装器
// BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, CharsetUtils.UTF_8)); OutputStreamWriter osw = new OutputStreamWriter(os, CharsetUtils.UTF_8); osw.write("some utf8 text");
Question : Why should we use OutputStreamWriter
over OutputStream
to write String? 问 :为什么要使用
OutputStreamWriter
过OutputStream
写字符串?
Thanks! 谢谢!
Question: Why should we use OutputStreamWriter over OutputStream to write String?
问题:为什么我们应该在OutputStream上使用OutputStreamWriter来编写String?
Simply to define the encoding only once in the constructor of OutputStreamWriter
instead of specifying each time we want to encode a String
into UTF-8
thanks to getBytes(Charsets.UTF_8)
只需在
OutputStreamWriter
的构造函数中仅定义一次编码,而无需指定每次我们都要使用getBytes(Charsets.UTF_8)
将String
编码为UTF-8
Moreover an OutputStreamWriter
provides many convenient methods to write String
such as write(String)
, write(String, int, int)
, append(CharSequence)
and append(CharSequence, int, int)
that you don't have in an OutputStream
. 另外一个
OutputStreamWriter
提供了许多方便的方法来写String
,如write(String)
, write(String, int, int)
append(CharSequence)
和append(CharSequence, int, int)
不要在有OutputStream
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.