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对象,是被关闭了的。
BufferedWriter中write与close函数使用
原文:https://www.cnblogs.com/dengjk/p/10432926.html