轉載請註明原文地址: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() 刷新該流的緩衝。