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();
}