Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileOutputStream: Does the "close" method calls also "flush"?

Tags:

I'm really confused about flush and close method.In my code I always close my FileOutputStream object. But I want to know that if I have to use flush method here, and where can I use it?

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?

try {     InputStream inputStream = con.getInputStream();     FileOutputStream outputStream = new FileOutputStream("C:\\programs\\TRYFILE.csv");      int bytesRead = -1;     byte[] buffer = new byte[4096];     while ((bytesRead = inputStream.read(buffer)) != -1) {     outputStream.write(buffer, 0, bytesRead); }  } catch(Exception e) {     // } finally {     outputStream.close();     inputStream.close(); }     

Note that the code works well: it download the file successfully. But I'm not sure about using flush.

like image 890
javauser35 Avatar asked Jul 16 '15 14:07

javauser35


People also ask

Does Close Call flush?

Its close() method does NOT call flush() .

What does Fileoutputstream flush do?

flush() method flushes this output stream and forces any buffered output bytes to be written out.

What is the difference between close and flush?

flush() writes the content of the buffer to the destination and makes the buffer empty for further data to store but it does not closes the stream permanently. That means you can still write some more data to the stream. But close() closes the stream permanently.

Does Fileoutputstream need to be closed?

No. It is not require to close other components.


1 Answers

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.

like image 77
Davide Lorenzo MARINO Avatar answered Sep 17 '22 17:09

Davide Lorenzo MARINO