Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is flush() call necessary when using try-with-resources

Will try-with-resources call flush() implicitly?

If it does, in the following code snippet, bw.flush() can be safely removed?

static void printToFile1(String text, File file) {     try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {         bw.write(text);         bw.flush();     } catch (IOException ex) {         // handle ex     } } 

ps. I don't see any description about it in official document:

https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html https://docs.oracle.com/javase/8/docs/api/java/lang/AutoCloseable.html

like image 620
petertc Avatar asked Sep 01 '15 05:09

petertc


People also ask

What is the use of the flush () method?

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.

What is the purpose of the flush () method in Java?

The flush() method of PrintWriter Class in Java is used to flush the stream. By flushing the stream, it means to clear the stream of any element that may be or maybe not inside the stream. It neither accepts any parameter nor returns any value.

What is the importance of flush ()?

While you are trying to write data to a Stream using the BufferedWriter object, after invoking the write() method the data will be buffered initially, nothing will be printed. The flush() method is used to push the contents of the buffer to the underlying Stream.

Does try with resources need close?

The try -with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try -with-resources statement ensures that each resource is closed at the end of the statement.


1 Answers

Closeable and AutoCloseable are general-purpose interfaces that do not know anything about flushing. So you can't find any information about it in their documentation - except some words about releasing resources.

A Writer on the other hand is a more specific-purpose abstract class that now knows something about flushing. Some excerpt of the documentation for the method Writer.close():

Closes the stream, flushing it first.

So - yes - when using a writer, a close will always also flush. This basically means that you have to consult the documentation of the concrete classes that you are using when trying to find out what closing really does.

like image 66
Seelenvirtuose Avatar answered Sep 22 '22 15:09

Seelenvirtuose