This week's book giveaway is in the General Computing forum.
We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes I/O: flush() and close() Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "I/O: flush() and close()" Watch "I/O: flush() and close()" New topic
Author

I/O: flush() and close()

Matthew Alesi
Ranch Hand

Joined: Sep 13, 2006
Posts: 38
Learning file I/O from K&B, and was a little confused on one point: the book goes out of its way to mention that a FileWriter must be flushed and closed when you are done using it, but I read somewhere else that the close() method automatically calls flush().

If this is true, why the unnecessary emphasis on calling both flush() and close() in the examples in the book? Just want to make sure I'm not missing something important.

Thanks!!


-Matt
Current CS undergrad
SCJP 5.0
Deepak Bala
Bartender

Joined: Feb 24, 2006
Posts: 6603
    
    1

Its likely that anything that is a closeable implements a Closeable interface.

Have a look at this interface...

http://java.sun.com/j2se/1.5.0/docs/api/java/io/Closeable.html

It is not mandatory for the close() function to call flush(). So its better to call flush() before you call close() to clear out the buffer.

Also, have a look at the Flushable interface. Anything with a flush() is likely to implement Flushable

http://java.sun.com/j2se/1.5.0/docs/api/java/io/Flushable.html

Both these interfaces have only one method and do not depend on each other.


SCJP 6 articles - SCJP 5/6 mock exams - SCJP Mocks - SCJP 5 Mock exam (Word document ) - SCJP 5 Mock exam in Java.Inquisition format
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: I/O: flush() and close()
 
Similar Threads
When to use flush() in Java?
file created,but nothing inside
Does fileWriter.flush() is always necessary?
flushes on close
Trouble writing to a text file