permaculture playing cards*
The moose likes Java in General and the fly likes When to use flush() in Java? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "When to use flush() in Java?" Watch "When to use flush() in Java?" New topic
Author

When to use flush() in Java?

abalfazl hossein
Ranch Hand

Joined: Sep 06, 2007
Posts: 635
When to use flush() in JAVA?When usage of that is necessary?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40052
    
  28
It probably varies from class to class. Here is an example of flush(). What happens is that a buffer might be full, with unread data still in it Flushing that moves all the data out into its destination, emptying the stream or whatever.
You don't usually have to call flush() if you call close().
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3649
    
  17

Here's one concrete example.

Let's say you have a BufferedOutputStream wrapped around a Socket's OutputStream. You want to send a load of data, but you don't want to close the connection yet.
After you're done writing everything you want to send, some data may still be in the buffer. Now you will have to flush the buffer, to force it to send all the data.
abalfazl hossein
Ranch Hand

Joined: Sep 06, 2007
Posts: 635
Thanks stephan, Nice example!

You don't usually have to call flush() if you call close().


Do you mean by using close(), buffer will be empty?
Tom Reilly
Rancher

Joined: Jun 01, 2010
Posts: 618
close() calls flush().
abalfazl hossein
Ranch Hand

Joined: Sep 06, 2007
Posts: 635


If I don't use flush in this code, It does not print anything.
If I use close, It only prints JAVA.
Only If i use flush, It works well. Why?
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19785
    
  20

Were you calling close() inside the loop? If so, try calling it after the loop.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
abalfazl hossein
Ranch Hand

Joined: Sep 06, 2007
Posts: 635


It works
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: When to use flush() in Java?