Java IO流 flush()的作用和缓冲流

Java 缓冲流和flush()的作用

哪些流是缓冲流,哪些流带有缓冲区?

根据Java官方文档关于Buffered Streams的介绍,缓冲流有四种:

  • BufferedInputStream:包装字节输入流
  • BufferedOutputStream:包装字节输出流
  • BufferedReader:包装字符输入流
  • BufferedWriter:包装字符输出流
    这些流又被称为包装流/处理流,用于包装非缓冲的流

There are four buffered stream classes used to wrap unbuffered streams: BufferedInputStream and BufferedOutputStream create buffered byte streams, while BufferedReader and BufferedWriter create buffered character streams.
——JAVA Documentation:Basic I/O

所以被包装流包装过的流都是使用缓冲区的;
缓冲流使用缓冲区;
字节流默认不使用缓冲区;
字符流使用缓冲区。

flush()方法的作用

flush():冲洗缓冲区,强制将缓冲区中的数据全部写入目标位置,清空缓冲区,不关闭流对象;

为什么用flush():在使用Bufferd Streams输出流对象时,我们需要对缓冲区进行冲洗,因为我们读取数据时,数据会先被读取在缓冲区中,为了确保输出流中的数据被全部写入,要flush缓冲区,否则数据会停留在缓冲区,不会输出,导致数据损失;

flush() :To flush output stream, use void flush() method of DataOutputStream class. This method internally calls flush() method of underlying OutputStream class which forces any buffered output bytes to be written in the stream.
源自:https://stackoverflow.com/a/9272658/21906030

Flushing Buffered Streams
It often makes sense to write out a buffer at critical points, without waiting for it to fill. This is known as flushing the buffer.
.
Some buffered output classes support autoflush, specified by an optional constructor argument. When autoflush is enabled, certain key events cause the buffer to be flushed. For example, an autoflush PrintWriter object flushes the buffer on every invocation of println or format. See Formatting for more on these methods.
.
To flush a stream manually, invoke its flush method. The flush method is valid on any output stream, but has no effect unless the stream is buffered
——JAVA Documentation:Basic I/O

热门相关:无量真仙   名门天后:重生国民千金   夫人你马甲又掉了   横行霸道   最强反套路系统