转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/5827509.html html
public class OutputStreamWriter extends Writer { // 流编码类,全部操做都交给它完成。 private final StreamEncoder se; // 建立使用指定字符的OutputStreamWriter。 public OutputStreamWriter(OutputStream out, String charsetName) throws UnsupportedEncodingException { super(out); if (charsetName == null) throw new NullPointerException("charsetName"); se = StreamEncoder.forOutputStreamWriter(out, this, charsetName); } // 建立使用默认字符的OutputStreamWriter。 public OutputStreamWriter(OutputStream out) { super(out); try { se = StreamEncoder.forOutputStreamWriter(out, this, (String)null); } catch (UnsupportedEncodingException e) { throw new Error(e); } } // 建立使用指定字符集的OutputStreamWriter。 public OutputStreamWriter(OutputStream out, Charset cs) { super(out); if (cs == null) throw new NullPointerException("charset"); se = StreamEncoder.forOutputStreamWriter(out, this, cs); } // 建立使用指定字符集编码器的OutputStreamWriter。 public OutputStreamWriter(OutputStream out, CharsetEncoder enc) { super(out); if (enc == null) throw new NullPointerException("charset encoder"); se = StreamEncoder.forOutputStreamWriter(out, this, enc); } // 返回该流使用的字符编码名。若是流已经关闭,则此方法可能返回 null。 public String getEncoding() { return se.getEncoding(); } // 刷新输出缓冲区到底层字节流,而不刷新字节流自己。该方法能够被PrintStream调用。 void flushBuffer() throws IOException { se.flushBuffer(); } // 写入单个字符 public void write(int c) throws IOException { se.write(c); } // 写入字符数组的一部分 public void write(char cbuf[], int off, int len) throws IOException { se.write(cbuf, off, len); } // 写入字符串的一部分 public void write(String str, int off, int len) throws IOException { se.write(str, off, len); } // 刷新该流。能够发现,刷新缓冲区实际上是经过流编码类的flush()实现的,故能够看出,缓冲区是流编码类自带的而不是OutputStreamWriter实现的。 public void flush() throws IOException { se.flush(); } // 关闭该流。 public void close() throws IOException { se.close(); } }
每次调用 write() 方法都会致使在给定字符(或字符集)上调用编码转换器。在写入底层输出流以前,获得的这些字节将在缓冲区中累积(传递给 write() 方法的字符没有缓冲,输出数组才有缓冲)。为了得到最高效率,可考虑将 OutputStreamWriter 包装到 BufferedWriter 中,以免频繁调用转换器。数组
2)BufferedWriter缓存
带缓冲的字符输出流:与OutputStreamWriter的缓冲不一样,BufferedWriter的缓冲是真正由本身建立的缓冲数组来实现的。故此:不须要频繁调用编码转换器进行缓冲,并且,它能够提供单个字符、数组和字符串的缓冲(编码转换器只能缓冲字符数组和字符串)。函数
BufferedWriter能够在建立时把一个OutputStreamWriter进行包装,为输出流创建缓冲;优化
而后,经过this
void write(char[] cbuf, int off, int len) 写入字符数组的某一部分。 void write(int c) 写入单个字符。 void write(String s, int off, int len) 写入字符串的某一部分。
向缓冲区写入数据。编码
还能够经过spa
void newLine()
写入一个行分隔符。 code
最后,能够手动控制缓冲区的数据刷新:视频
void flush() 刷新该流的缓冲。