IO流操作flush应用场景

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

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

  • flush:刷新缓冲区,流对象可以继续使用。
  • close: 先刷新缓冲区,然后通知系统释放资源。流对象不可以再被使用了。
@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 @ 2024-02-22 15:40  港城大白鲨  阅读(17)  评论(0编辑  收藏  举报