当前位置:网站首页>对OutputStream类的flush()方法的误解
对OutputStream类的flush()方法的误解
2022-04-23 07:34:00 【beinlife】
最近使用java的FileOutputStream写文件,调用到了flush()方法。
于是查看了FileInputStream类的源代码,发现flush()其实是继承于其父类OutputStream的。
而OutputStream类的flush()却什么也没做,恍然大悟,真是“看源代码者得真相啊”。
其实flush()是Flushable接口的方法,官方文档的对该方法的注释是“Flushes this output stream and forces any buffered output bytes to be written out.”。
OutputStream方法实现了Flushable接口,而又什么也没做,真是让人一头雾水,于是就出现了我的误解。
那么什么时候flush()才有效呢?
答案是:当OutputStream是BufferedOutputStream时。
当写文件需要flush()的效果时,需要
FileOutputStream fos = new FileOutputStream("c:\a.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos);
也就是说,需要将FileOutputStream作为BufferedOutputStream构造函数的参数传入,然后对BufferedOutputStream进行写入操作,才能利用缓冲及flush()。
查看BufferedOutputStream的源代码,发现所谓的buffer其实就是一个byte[]。
BufferedOutputStream的每一次write其实是将内容写入byte[],当buffer容量到达上限时,会触发真正的磁盘写入。
而另一种触发磁盘写入的办法就是调用flush()了。
版权声明
本文为[beinlife]所创,转载请带上原文链接,感谢
https://blog.csdn.net/beinlife/article/details/52678567
边栏推荐
- AAAI 2022招募讲者啦!!
- Talk about the basic but not simple stock data
- Goland 调试go使用-大白记录
- dried food! Point based: differentiable Poisson solver
- 1216_ MISRA_ C standard learning notes_ Rule requirements for control flow
- The following program deletes n consecutive words starting from the ith character from the string str
- LeetCode15. Sum of three
- 利用Js实现一个千分位
- 万物互联下如何对设备进行加密
- nn.Module类的讲解
猜你喜欢
干货!以点为形:可微分的泊松求解器
[untitled]
搜一下导航完整程序源码
【深度好文】Flink SQL流批⼀体化技术详解(一)
分布式消息中间件框架选型-数字化架构设计(7)
Weekly leetcode - 06 array topics 7 ~ 739 ~ 50 ~ offer 62 ~ 26 ~ 189 ~ 9
396. Rotate Function
Community group purchase applet source code + interface DIY + nearby leader + supplier + group collage + recipe + second kill + pre-sale + distribution + live broadcast
1216_ MISRA_ C standard learning notes_ Rule requirements for control flow
Qt读写XML文件
随机推荐
5.6 comprehensive case - RTU-
欧圣电气深交所上市:市值52亿 陆为东父女为美国籍
利用Js实现一个千分位
Detailed explanation of ansible automatic operation and maintenance (I) installation and deployment, parameter use, list management, configuration file parameters and user level ansible operating envi
Smart business card applet business card details page function implementation key code
freertos学习02-队列 stream buffer message buffer
ApplicationReadyEvent的使用
【学习】从零开始的音视频开发(9)——NuPlayer
扎心了!一女子发朋友圈羡慕别人按时发工资被开除,连点赞的同事也一同被开除了...
LeetCode中等题之旋转函数
剑指offer day24 数学(中等)
岛屿的个数
通过实现参数解析器HandlerMethodArgumentResolver接口来自定义注解
Find the largest of 3 strings (no more than 20 characters per string).
Vowel substring in statistical string of leetcode simple problem
总线结构概述
QT reads all files under the path or files of the specified type (including recursion, judging whether it is empty and creating the path)
Weekly leetcode - 06 array topics 7 ~ 739 ~ 50 ~ offer 62 ~ 26 ~ 189 ~ 9
QFileDialog 选择多个文件或文件夹
LeetCode-199-二叉树的右视图