简体   繁体   English

用Java将字符串写入OutputStream的最佳方法

[英]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种方法:

  1. Use OutputStream itself 使用OutputStream本身

     // write String os.write("some utf8 text".getBytes(Charsets.UTF_8)); 
  2. 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? :为什么要使用OutputStreamWriterOutputStream写字符串?

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.

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