2

After I'm done using a BufferedWriter, I know I should call writer.close(). But should I also call writer.flush()? Or is it unnecessary?

Also, does it matter if I do this inside the try block containing the instantiation of the stream and the IO code - or outside of it?

Aviv Cohn
  • 15,543
  • 25
  • 68
  • 131

3 Answers3

3

Close will automatically flush your stream, so yoou dont have to flush the stream while closing. Flush is useful when you are in the middle of writing to a stream and want to push the intermediate values to the file/output stream, so that if the program crashes the data wont be lost.

From Java 7 and higher you can make use of try-with-resources to avoid writing the clean up code for cleaning up the streams.

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.

user2864740
  • 60,010
  • 15
  • 145
  • 220
Kakarot
  • 4,252
  • 2
  • 16
  • 18
  • Does it matter if I call writer/reader.close() inside or outside of the `try` block containing the IO code and the writer/reader instantiation? – Aviv Cohn Apr 11 '14 at 21:30
  • 1
    If you are using JDK 7 and aboe, use try with resource, that will save you the effort of writing the code to cleanup/close the stream. – Kakarot Apr 11 '14 at 21:31
  • Thanks, but anyway could you answer my last question? – Aviv Cohn Apr 11 '14 at 21:34
  • 1
    ideally stream should be closed in finally block so that even if there is some exception it will be closed in the finally block. – Kakarot Apr 11 '14 at 21:35
3

From what I've experienced, you should call flush only when you want/need to make sure the current data must be written in the stream. When you work with small files, you will just call close directly since this already triggers a flush on the file stream before writing it. But when you work with bigger files e.g. a file having 1 million lines or more, then it would be better calling flush from time to time (e.g. after writing 10k lines), in order to write to disk and ease the final flush called by close. This can be done in case the program crashes.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
2

The Methode close() will call (f)flush() automatic

ArmandoS63
  • 693
  • 1
  • 6
  • 21