Java IO:IO流中的flush方法 .(三)

2014-11-24 09:14:55 · 作者: · 浏览: 1
Bytes();
continue;
}
cr.throwException();
}
}

void implFlushBuffer() throws IOException {
if (bb.position() > 0)
writeBytes();
}

void implFlush() throws IOException {
implFlushBuffer();
if (out != null)
out.flush();
}

void implClose() throws IOException {
flushLeftoverChar(null, true);
try {
for (;;) {
CoderResult cr = encoder.flush(bb);
if (cr.isUnderflow())
break;
if (cr.isOverflow()) {
assert bb.position() > 0;
writeBytes();
continue;
}
cr.throwException();
}

if (bb.position() > 0)
writeBytes();
if (ch != null)
ch.close();
else
out.close();
} catch (IOException x) {
encoder.reset();
throw x;
}
}

String encodingName() {
return ((cs instanceof HistoricallyNamedCharset)
((HistoricallyNamedCharset)cs).historicalName()
: cs.name());
}

更多源2. Writer类的flush方法

该类是一个抽象类,声明如下:

[java]
public abstract class Writer implements Appendable, Closeable, Flushable
[java]
public abstract class Writer implements Appendable, Closeable, Flushable

Writer类的flush()方法是一个抽象方法,其子类一般都实现了该方法。所以,一般使用字符流之后,调用一下flush()或者close()方法。

[java]
abstract public void flush() throws IOException;
[java]
abstract public void flush() throws IOException;

细节请看jdk的api,或者Java的源码以及上面的StreamEncoder类源码。

ok,说到这里吧,这里主要借助Java的IO中字节流与字符流的flush()方法,来说明学Java看源码和思考是很重要的。

总之,不管你使用哪种流(字符、字节、具有缓冲的流)技术,不妨调用一下flush()/close()方法,防止数据无法写到输出流中。