BufferedWriter 是一個緩沖字符輸出流,可以將要輸出的內容先緩沖到一個字符數組中,等字符數組滿了才一次性寫到輸出流內,默認的字符數組長度為8192。使用BufferedWriter 時需要對write與close函數有一定了解,看如下代碼:
StringBuffer content = new StringBuffer(); BufferedWriter bWriter = new BufferedWriter(new FileWriter(file, false)); content.setLength(0); bWriter.write(content.toString()); bWriter.close();
問題:
1. BufferedWriter write函數寫入空字符串時會怎么樣?
2. BufferedWriter close函數能否關閉FileWriter的文件流 ?
源代碼(jdk1.6)解讀:
public void write(String paramString) throws IOException { write(paramString, 0, paramString.length());
} public void write(String arg0, int arg1, int arg2) throws IOException {
Object arg3 = this.lock; synchronized (this.lock) { this.ensureOpen(); int arg4 = arg1; int arg5 = arg1 + arg2;
while (arg4 < arg5) { int arg6 = this.min(this.nChars - this.nextChar, arg5 - arg4); arg0.getChars(arg4, arg4 + arg6, this.cb, this.nextChar); arg4 += arg6; this.nextChar += arg6; if (this.nextChar >= this.nChars) { this.flushBuffer(); } } } }
答案1:content.setLength(0) 將字符串content 的長度設置為0,content不為null,所以content.toString()為'',一個空字符串。bWriter.write寫入null會報錯,但是寫入''時不會報錯,從源代碼中可以看到當寫入長度為0的字符串時,arg4==arg5,循環不會執行,也不會報錯,能夠正常處理。
public void close() throws IOException { Object arg0 = this.lock; synchronized (this.lock) { if (this.out != null) { try { Writer arg1 = this.out; Throwable arg2 = null; try { this.flushBuffer(); } catch (Throwable arg21) { arg2 = arg21; throw arg21; } finally { if (arg1 != null) { if (arg2 != null) { try { arg1.close(); } catch (Throwable arg20) { arg2.addSuppressed(arg20); } } else { arg1.close(); } } } } finally {
this.out = null; this.cb = null; } } } }
答案2:當BufferedWriter 關閉時,bWriter.close函數能夠關閉FileWriter的文件流。從源代碼中可以看出,bWriter.close()在close時會調用關閉FileWriter文件輸出流, 其中,this.out 就是FileWriter對象,是被關閉了的。