Labels

Thursday, July 12, 2012

What is Flush Streams in java?

This might seem obvious, but it repeatedly kicks my butt. The problem usually appears with two programs on either side of a network socket having some kind of conversation. If you don't flush the output stream every time you say something, the data may not actually get written out to the socket, and the two programs will sit patiently, waiting forever for something to happen.
Typically, you can just call flush() after you write something important:
// OutputStream out;
// byte[] data
out.write(data);
out.flush();

If you're writing text data, you might use a PrintWriter for output. PrintWriter has a special constructor that lets you specify if the stream should be flushed after every newline:
PrintWriter out = new PrintWriter(rawOut, true);
A PrintWriter created in this way will automatically flush itself whenever you write a line of text.

No comments:

Post a Comment