FileOutputStream: Does the “close” method calls also “flush”?

喜欢而已 提交于 2019-11-28 06:54:21

The method flush is used to "flush" bytes retained in a buffer. FileOutputStream doesn't use any buffer, so flush method is empty. Calling it or not doesn't change the result of your code.

With buffered writers the method close call explicitly flush.

So you need to call flush when you like to write the data before closing the stream and before the buffer is full (when the buffer is full the writer starts writing without waiting a flush call).

The source code of class FileOutputStream hasn't a custom version of method flush. So the flush method used is the version of its super class OutputStream. The code of flush in OutputStream is the following

public void flush() throws IOException {
}

As you see this is an empty method doing nothing, so calling it or not is the same.

I will write a project that download 4 or 5 files repeatedly. I will write a method(for download files) and my method will be in a loop and download files repeatedly.My method will have a code like this.

Does the close method calls flush, or do I have to use flush before closing?

I recommend to use the NIO.2 API and the try-with-resources statement. This will reduce the amount of code and takes care of flushing and closing the streams:

try (InputStream inputStream = con.getInputStream()){
    Files.copy(inputStream, Paths.get("C:\\programs\\TRYFILE.csv"));
}

The topic is a bit confusing since OutputStream.close does indeed not require an automatic flush, but subclasses might specify that. They might also provide a flush method which does nothing (e.g. as the one inherited from OutputStream, which is the case for FileOutputStream). In this case it has no effect to call the flush method, of course, so you can omit it.

If in doubt (if you don't know which subclass you're working with) I guess it's better to call the flush manually.

But again, using the code above this is taken care for you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!