Reputation: 13854
I was looking some methods of PrintStream class and came across write() and as per the docs to print in the console we need to call System.out.flush();
.But my doubt is if I write these lines
System.out.write(40);
System.out.write(10);
Then also (
gets printed.I know 10
represents new line but I wanted to know why it only happens with new line.If I write
System.out.write(40);
System.out.write(32); 32 for space then also nothing gets printed.
Upvotes: 2
Views: 94
Reputation: 5095
From the docs.
public void write(int b)
Writes the specified byte to this stream. If the byte is a newline and automatic
flushing is enabled then the flush method will be invoked.
Upvotes: 1
Reputation: 77226
This appears to be a race condition in PrintStream
. The (OpenJDK 6) PrintStream
code forces a flush of the underlying OutputStream
whenever the output written includes the character \n
, but not any other time, and there's no sort of finalizer that ensures that buffered output in the BufferedOutputStream
the JVM wraps around standard output gets flushed when the JVM exits.
The code that initializes the System
class uses a 128-byte buffer for System.out
, and if you output enough characters to fill the buffer (I inserted a 128-count for
loop around writing the (
character), you'll see the output on the terminal.
Upvotes: 1
Reputation: 11775
From the PrintStream.write
:
if ((b == '\n') && autoFlush)
out.flush();
}
So if you write a new-line to a System.out
it will be auto-flushed.
Btw javadoc says that too:
Writes the specified byte to this stream. If the byte is a newline and automatic flushing is enabled then the flush method will be invoked.
Upvotes: 5
Reputation: 20651
Probably the output stream is line-buffered - that is, it automatically flushes when it sees an end-of-line. To guarantee your ouput you should always use flush().
Upvotes: 1