| Author |
When to use flush() in Java?
|
abalfazl hossein
Ranch Hand
Joined: Sep 06, 2007
Posts: 602
|
|
|
When to use flush() in JAVA?When usage of that is necessary?
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32712
|
|
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: 3056
|
|
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: 602
|
|
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: 602
|
|
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: 19216
|
|
|
Were you calling close() inside the loop? If so, try calling it after the loop.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
abalfazl hossein
Ranch Hand
Joined: Sep 06, 2007
Posts: 602
|
|
It works
|
 |
 |
|
|
subject: When to use flush() in Java?
|
|
|