• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

When to use flush() in Java?

 
abalfazl hossein
Ranch Hand
Posts: 635
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When to use flush() in JAVA?When usage of that is necessary?
 
Campbell Ritchie
Sheriff
Pie
Posts: 49827
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 6127
74
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 635
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 618
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
close() calls flush().
 
abalfazl hossein
Ranch Hand
Posts: 635
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Pie
Posts: 20611
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Were you calling close() inside the loop? If so, try calling it after the loop.
 
abalfazl hossein
Ranch Hand
Posts: 635
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


It works
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic