Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between flush and close function in case of filewriter in java

Tags:

java

io

People also ask

What is Filewriter flush in Java?

This method is used to flush the writer, which means that this method will remove all the data present inside the writer. It neither accepts any parameter nor returns any value.

Do we need to close Filewriter in Java?

It is not necessary to close it, because BufferedWriter takes care of closing the writer it wraps.

What is flush () Java?

flush() method flushes the stream. If the stream has saved any characters from the various write() methods in a buffer, write them immediately to their intended destination. Then, if that destination is another character or byte stream, flush it.


flush() just makes sure that any buffered data is written to disk (in this case - more generally, flushed through whatever IO channel you're using). You can still write to the stream (or writer) afterwards.

close() flushes the data and indicates that there isn't any more data. It closes any file handles, sockets or whatever. You then can't write to the stream (or writer) any more.

Note that without calls to flush() data can still be written to the IO channel in question - it's just that some data might be buffered.

close() generally calls flush() as well, but it's recently been pointed out to me that in some JDK implementations, any exceptions thrown by flushing as part of closing are swallowed :(


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. If you want to write some data further, then you have to reopen the stream again and append the data with the existing ones.


flush() flushes content of buffer to destination.And you can write something again into the stream.close() flushes content to destination and closes the stream. After close() you can't write anything anymore.


flush() :To flush output stream, use void flush() method of DataOutputStream class. This method internally calls flush() method of underlying OutputStream class which forces any buffered output bytes to be written in the stream.

close() :It generally close the Stream,connection,socket.

See flush and close example