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
本文作者:凉白茶
本文链接:https://www.cnblogs.com/zh-Note/p/17403308.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步