最近在用kotlin编写从assets复制文件到CacheDir的代码,想在StackOverflow上找一下最佳实践,发现有的人在调用input.copyTo(output, 1024)
之后会调用output.flush()
而有的人不会,于是研究了一下这个问题:FileOutputStream是否需要flush和close?
答案:需要close()
但不需要flush()
。因为在FileOutputStream
中,override了close
方法进行了一些操作比如关闭channel等等,没有overrideflush
方法;而在它的父类OutputStream
的代码中,close
和flush
的实现均为空。
OutputStream.java
/**
* 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.
* 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.
* The <code>flush</code> method of <code>OutputStream</code> does nothing.
*
* @exception IOException if an I/O error occurs.
*/
public void flush() throws IOException {
}
/**
* Closes this output stream and releases any system resources
* associated with this stream. The general contract of <code>close</code>
* is that it closes the output stream. A closed stream cannot perform
* output operations and cannot be reopened.
* The <code>close</code> method of <code>OutputStream</code> does nothing.
* @exception IOException if an I/O error occurs.
*/
public void close() throws IOException {
}
FileOutputStream.java
public void close() throws IOException {
synchronized (closeLock) {
if (closed) {
return;
}
closed = true;
}
// Android-added: CloseGuard support.
guard.close();
if (channel != null) {
channel.close();
}
// BEGIN Android-changed: Close handling / notification of blocked threads.
if (isFdOwner) {
IoBridge.closeAndSignalBlockedThreads(fd);
}
// END Android-changed: Close handling / notification of blocked threads.
}