flush,close方法

来源:3-14 缓冲流案例

饭勺超人

2018-01-25 01:36:08

 package com.mawenqiang.file;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class OutputStreamDemo {
 public static void main(String[] args) {
  try {
   // 不使用缓冲输出流进行文件写入操作
   FileOutputStream fos = new FileOutputStream(new File("one.txt"), true);
   long startTime = System.currentTimeMillis();
   for (int i = 0; i < 10000; i++) {
    fos.write(i);
   }
   fos.close();
   long endTime = System.currentTimeMillis();
   System.out.println("不适用缓冲输出流操作用时:" + (endTime - startTime));
   // 使用缓冲输出流进行文件写入操作
   FileOutputStream fos1 = new FileOutputStream(new File("two.txt"), true);
   BufferedOutputStream bos = new BufferedOutputStream(fos1);
   startTime = System.currentTimeMillis();
   for (int i = 0; i < 10000; i++) {
    bos.write(i);
   }
//   bos.flush();
   fos1.close();
   bos.close();
   endTime = System.currentTimeMillis();
   System.out.println("使用缓冲输出流操作用时:" + (endTime - startTime));
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

在使用缓冲输出流写入数据时,写入操作完成,直接调用bos.close()方法,抛出异常,只有先调用bos.flush();然后bos.close();

看文档当缓冲输出流直接调用close方法时首先调用flush方法,然后调用close方法,

The close method of FilterOutputStream calls its flush method, and then calls the close method of its underlying output stream.不知道这样理解对不

写回答

2回答

THappy

2018-01-25

fos1输出流是比bos输出流先开的,先开的流要后关,所以fos1.close();与bos.close();要交换位置。

另外,虽然一般输出流不调用flush()直接调用close()也是可以的,但为了保证程序正常我们一般都会先调用flush()方法,然后再调用close()方法,这也是一个良好的编程习惯~祝学习愉快~

0

饭勺超人

提问者

2018-01-25

你好,可以这么理解么,bos是依据fos1创建的,所以要先关bos,后关fos1?

0
hHappy
h 可以的~~
h018-01-25
共1条回复

0 学习 · 14452 问题

查看课程