FileOutputStream是否需要flush和close?

最近在用kotlin編寫從assets復(fù)制文件到CacheDir的代碼,想在StackOverflow上找一下最佳實踐,發(fā)現(xiàn)有的人在調(diào)用input.copyTo(output, 1024)之后會調(diào)用output.flush()而有的人不會,于是研究了一下這個問題:FileOutputStream是否需要flush和close?
答案:需要close()但不需要flush()。因為在FileOutputStream中,override了close方法進(jìn)行了一些操作比如關(guān)閉channel等等,沒有overrideflush方法;而在它的父類OutputStream的代碼中,closeflush的實現(xiàn)均為空。

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.
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容