Java-J2SE-IO-drain()和flush()

本文深入探讨了Java中ObjectOutputStream的drain()与flush()方法的实现细节与区别。drain()方法将当前流中的所有缓冲数据写入底层流,但不执行底层流的flush操作;而flush()方法则会强制将当前输出流缓冲区中的所有数据写入底层流,并确保数据被完全写入预期目标,如文件。

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值