Javadoc中關於這兩個方法的描述如下
drain(): Drain any buffered data in ObjectOutputStream. Similar to flush but does not propagate the flush to the underlying stream. 將當前流中的所有緩衝數據寫入底層流,但不會對底層流執行flush.
flush(): Flushes this stream by writing any buffered output to the underlying stream.flush()方法強制將當前輸出流緩衝區中所有數據寫入底層流,若當前流已是最底層則將流中所有數據寫入預期目標中(如文件).
這裏選取ObjectOutputStream中的兩個有具體實現的drain()和flush()方法進行對比
drain()
/**
* Writes all buffered data from this stream to the underlying stream,
* but does not flush underlying stream.
* 將當前流中的所有緩衝數據寫入底層流(這裏底層流一般是FileOutputStream),但不會對底層流執行flush。
*/
void drain() throws IOException {
if (pos == 0) {
return;
}
if (blkmode) {
writeBlockHeader(pos);
}
//buf: 用於寫入常規/塊數據的緩衝區,是整個ObjectOutputStream的緩衝區
out.write(buf, 0, pos);
pos = 0;
}
flush()
/**
* Flushes the stream. This will write any buffered output bytes and flush
* through to the underlying stream.
* flush()方法強制將當前輸出流緩衝區中所有數據寫入底層流(這裏底層流一般是FileOutputStream)
* 若當前流已是最底層(如當前流是FileOutputStream)則將流中所有數據寫入預期目標中(如文件)
*/
public void flush() throws IOException {
bout.flush();
}