我想实例化一个缓冲的writer来写入socket输出流。
String cs = "UTF-8";
OutputStream out = socket.getOutputStream();
Writer writer1 = new BufferedWriter(
new OutputStreamWriter(out, cs));
Writer writer2 = new OutputStreamWriter(
new BufferedOutputStream(out), cs);
Writer writer3 = new BufferedWriter(
new OutputStreamWriter(
new BufferedOutputStream(out), cs));
第一版和第二版之间是否存在非明显差异?哪一个更适合写入套接字?第三个版本有点“矫枉过正”吗?
答案 0 :(得分:5)
第三个是矫枉过正。
第一个是首选,因为它在通过文本到字节编码器发送之前缓冲数据,这在块中完成时比一次一个字符更好。
OutputStreamWriter
的javadoc甚至这样说:
为了获得最高效率,请考虑在BufferedWriter中包装OutputStreamWriter,以避免频繁的转换器调用。例如:
Writer out = new BufferedWriter(new OutputStreamWriter(System.out));