IO流操作flush应用场景

一、刷新(flush)与关闭(close)

在进行IO流操作的时候,经常会遇到flush()和close()方法,有时候会搞不清什么时候需要flush,索性就所有时候都flush

  • flush:刷新缓冲区,流对象可以继续使用。
  • close: 先刷新缓冲区,然后通知系统释放资源。流对象不可以再被使用了。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@Test
public void t3() throws IOException {
    FileWriter fileWriter = new FileWriter("D:\\temp\\temp2.txt",true);
    fileWriter.write("你好,你是一个好人");
    fileWriter.flush();//正确示范
    fileWriter.write("hello world");
    fileWriter.close();
}
@Test
public void t4() throws IOException {
    FileOutputStream fileOutputStream = new FileOutputStream("D:\\temp\\temp2.txt");
    fileOutputStream.write("你好,你是一个好人".getBytes());
    fileOutputStream.flush();//错误示范
    fileOutputStream.write("hello world".getBytes());
    fileOutputStream.close();
}
@Test
public void t5() throws IOException {
    FileOutputStream fileOutputStream = new FileOutputStream("D:\\temp\\temp2.txt");
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
    bufferedOutputStream.write("你好,你是一个好人".getBytes());
    fileOutputStream.flush();//错误示范
    bufferedOutputStream.write("hello world".getBytes());
    fileOutputStream.close();
}

 

在close之前调用flush总没有错,只是会显得不规范,对代码理解不深

1. FileOutputStream 的flush方法是调用父类的一个空方法,自身并没有重写,所以调用这个方法是没有意义的

2. BufferedOutputStream里的flush是有意义的,但close方法里已经调用了这个flush,所以如果只是在关闭的时候可以不用刻意flush

那flush有哪些应用场景呢,比如代码1部分的 如果我想写一部份数据后就写入到文件系统可以手动调用flush(),之前的数据就会写入到文件,然后继续写。

posted @   港城大白鲨  阅读(224)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示