android - 在 Android 流中使用 flush() close() 的好处?

标签 android inputstream outputstream

我知道总体思路,但我不确定它是否有效果,因为 Android api 声明如下:“刷新此流。此方法的实现应确保写出任何缓冲数据。此实现不执行任何操作”

这个实现什么都不做 <-- 这是否意味着它没有用,或者我错过了什么?

最佳答案

如果您阅读 oracle 上的扩展文档

http://download.oracle.com/javase/1.4.2/docs/api/java/io/OutputStream.html#flush()

Flushes this output stream and forces any buffered output bytes to be written out. The general contract of flush 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.

The flush method of OutputStream does nothing.

意味着,方法本身什么都不做,而且是抽象的,所以任何底层类都可以实现自己版本的刷新流并强制它们写入(不在写入队列中等待)

但是无论如何,正如 Guillaume 指出的那样,无论如何调用它都是一种很好的做法。如果稍后,您将您的流替换为另一个使用它的实现,那么您会后悔的。

Depending on the OS, flush() does nothing more than force the data to be written to the OS.

flush() does nothing on FileOutputStream. It is only useful on buffered streams.

来自 close() 的 javadoc,请注意,如果您在之后立即关闭它,则不必刷新流。

Close the stream, flushing it first. Once a stream has been closed, further write() or flush() invocations will cause an IOException to be thrown. Closing a previously-closed stream, however, has no effect.

相关:
FileOutputStream.close is really slow when writing large file
flush in java.io.FileWriter

关于android - 在 Android 流中使用 flush() close() 的好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8181318/

相关文章:

java - 在单个输入流上使用多个 InputReader

java - 在java中,如何从输入流中读取固定长度并保存为文件?

java - 交替 PipedOutputStream PipedInputStream Numbers 示例

java - 编译时,Android Manifest 出现问题导致无法运行?

javascript - 在 Android 的 WebView 中通过 javascript 捕获页面重定向

Android 无法在屏幕上显示所有图像?

java - Android:异步任务执行doInBackground()时发生错误

java - 如何在 Java 中将 InputStream 读取/转换为字符串?

java - byte[] 到 Java 中的文件

java - 为什么 Java OutputStream.write() 需要整数但写入字节