Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
772 views
in Technique[技术] by (71.8m points)

eclipse - Java: synchronizing standard out and standard error

I have a strange problem and it would be nice if I could solve it. For the debugging purposes (and some other things, as well) I'm writing a log of a console Java application on the standard output. Some things that are writen on standard out, and some things like errors are printed on standard error. The problem is that these two are not perfectly synchronized, so the order of printed lines is not always correct. I guess this is because many things are printed and it happens that a buffer for one output is full so the other output prints before the first one flushes it buffer.

E.g., I want to write this:

syso: aaa
syso: bbb
syso: ccc
syso: ddd
syso: eee
syserr: ---

What is sometimes printed is

aaa
bbb
ccc
---
ddd
eee

Sometimes there is not a new line in between, so it looks like

aaa
bbb
ccc---

ddd
eee

Every time I print something on an output, I flush the same output with

System.out.flush();

or

System.err.flush();

How to solve this problem? Btw, everything is printed in the Eclipse console.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is that it's the responsibility of the terminal emulator (in your case, Eclipse) to process the standard output and the standard error of your application. Without communicating with the terminal emulator, you can never be sure that out and err are displayed in the right order. Therefore, I would consider printing everything on err and redirect it to a file. You can still use out for clean user interaction.

Nevertheless, there is a (very bad, but strict) solution to your problem:

System.out.println(...);
System.out.flush();
Thread.sleep(100);

System.err.println(...);
System.err.flush();
Thread.sleep(100);

You may have to change the sleep duration depending on your configuration!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...