Hi there, following is a code to display the messages entered by a user in the keyboard.
import java.io.*; public class InputTranslator { public static void main(String args[]) throws IOException { BufferedReader inStream = new BufferedReader(new InputStreamReader(System.in)); String inputLine; do { System.out.println(">"); System.out.flush(); inputLine=inStream.readLine(); System.out.println("your message is:" +inputLine); }while(inputLine.length()!=0); } } In this program, even if I comment the line System.out.flush(), I couldn't find the difference in the output. I exactly want to know what is happening in that statement. thanks in advance. sasiantony.
"sasiantony", The Java Ranch has thousands of visitors every week, many with surprisingly similar names. To avoid confusion we have a naming convention, described at http://www.javaranch.com/name.jsp . We require names to have at least two words, separated by a space, and strongly recommend that you use your full real name. Please choose a new name which meets the requirements. Thanks.
"flush()" causes any remaining characters which are waiting in a stream to actually be sent. Whether there are any characters waiting depends on what has been put into the stream, and what sort of stream it is. From your example it looks like System.out is not buffered, so characters are being sent as soon as they enter the stream. If you were to wrap System.out in a BufferedWriter, you might see a greater difference when you call "flush()". For example:
@Frank, I am still strugling as to why we're using system.out.flush().
you've said ( "flush()" causes any remaining characters which are waiting in a stream to actually be sent ) does it mean that if we don't use flush(), there might be a chance of loosing the data ?
Well, since Frank posted that reply nearly 13 years ago, it's possible he doesn't have the thread in his watch list any longer. So I'm going to take the liberty of trying to answer you.
There are situations where you might lose un-flushed data, yes. If you were writing to a file, say, and your program crashed before you closed the FileWriter, then you could lose the un-flushed data. Normally you don't need to worry about that because closing the FileWriter (and any other buffered output stream or writer) will automatically flush the buffers.
The other situation which occurs is that there might be something waiting to see the data you're writing. That was the original poster's question, I think. The most likely scenario for this case is where you're sending some data over the network to some other program which is going to do something with the data you send. If you don't flush the socket's output stream then the other program may wait indefinitely for the un-flushed data to arrive.