标题: java的io流中,什么时候应该在流关闭之前加flush,什么时候不用呢? [打印本页] 作者: zzm0717 时间: 2016-5-10 22:29 标题: java的io流中,什么时候应该在流关闭之前加flush,什么时候不用呢? 首先 解释下这个flush的作用
这个是java.io.OutputStream的 空实现(java.io.FileOutputStream使用的是java.io.OutputStream的实现 java.net.SocketOutputStream也是一样)
/**
* Flushes this output stream and forces any buffered output bytes
* to be written out. The general contract of <code>flush</code> is
* that calling it is an indication that, if any bytes previously
* written have been buffered by the implementation of the output
* stream, such bytes should immediately be written to their
* intended destination.
* <p>
* If the intended destination of this stream is an abstraction provided by
* the underlying operating system, for example a file, then flushing the
* stream guarantees only that bytes previously written to the stream are
* passed to the operating system for writing; it does not guarantee that
* they are actually written to a physical device such as a disk drive.
* <p>
* The <code>flush</code> method of <code>OutputStream</code> does nothing.
*
* @exception IOException if an I/O error occurs.
*/
public void flush() throws IOException {
}
这个是java.io.BufferedOutputStream的
/**
* Flushes this buffered output stream. This forces any buffered
* output bytes to be written out to the underlying output stream.
*
* @exception IOException if an I/O error occurs.
* @see java.io.FilterOutputStream#out
*/
public synchronized void flush() throws IOException {
flushBuffer();
out.flush();
}
为了防止过于频繁的写操作 所以Java提供了一个java.io.BufferedOutputStream类 内部持有一个缓冲区 默认不直接将数据写到硬盘上 而是存到缓冲区中 直到一定条件后触发(就是调用上面的flushBuffer()了) 也可以强制通过flush()方法提前触发
所以当你认为你完成了某一个比较重要的操作的时候 最好进行一次flush 防止数据在内存中丢失
========================以下是题外话=============================
以上全部都是在语言层面上做出的优化 实际运行中 操作系统也会做优化 并不是实际调用了write方法 数据就会落到硬盘上 因为操作系统有IO缓存 所以保证数据真正落地的方法不仅仅是调用flush 还要调用java.io.FileDescriptor#sync()方法 这个方法是本地方法 我没看实现 不过应该就跟下面这个链接里说的是一回事