views:

175

answers:

2

Hi,

I use Eclipse. When I have an application like this:

write 20 times 'Hello World\n' to stdout
write 'ERROR\n' to stderr
write 5 times 'Hello  World\n' to stdout

The output looks many times like this:

Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
...
Hello World
Hello World
Hello World
ERROR

Is there a way to synchronize these two output streams? Of course without waiting a few milliseconds after the block of 20 times Hello World and waiting a few milliseconds after printing ERROR.

+2  A: 

System.out and System.err are ordinary PrintStream objects (which provide a flush() method), so try System.out.flush() and System.err.flush().

aioobe
+3  A: 

For "serious" use, I prefer not writing directly to System.out/System.err, since it hard-codes the destination, and it also it uses the rather quirky PrintStream (is it a byte stream or a character stream?). If you wrap the output streams in your own PrintWriter, you can then set it to flush automatically - the second argument in the constructor is auto-flush.

E.g.

PrintWriter out = new PrintWriter(System.out, true);
PrintWriter err = new PrintWriter(System.err, true);

out.println("Hello world");
//this will flush after writing the end of line

See

mdma
*"is it a byte stream or a character stream?"*. It is clearly a byte stream. The methods that write characters, strings, numbers, etc do implicit conversions to bytes using the JVM's default charset.
Stephen C
@Stephen I was talking about it's client interface in java. `PrintWriter` allows for writing characters, `OutputStream` writes bytes, yet the interface provided by `PrintStream` writes both bytes and characters, but as you point out, if you write a string through the stream then you'll get bytes out the other end in the current default encoding. This is not a good thing and is an anomaly of the early jdk 1.0 design before i18n was complete, i18n brought a clear distinction between writing bytes and writing characters. Please see the second link for more on this.
mdma