设为首页 加入收藏

TOP

Java IO流 flush()的作用和缓冲流
2023-07-25 21:24:59 】 浏览:16
Tags:Java flush

Java 缓冲流和flush()的作用

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

  1. 哪些流是缓冲流
    根据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

  2. 哪些流带有缓冲区?

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

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

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Spring源码:Bean生命周期(四) 下一篇最近迷上了源码,Tomcat源码,看..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目