Java: System. out. println and System. err. println are confused in the output
There is a task: use the commands System.out.println and System.err.println to print the text in a red frame. Like like this:
*******
*текст*
*******
But when output to IDEA, the text always crashes before the frame, then after, then otherwise, but not according to the task. In Eclipse, I saw that it works. I understand that there is a problem in the threads, but I can't solve it.
System.err.print("*******\n");
System.err.print("|");
System.out.print("text");
System.err.print("|");
System.err.print("*******\n");
3 answers
Try this (clear the buffer after each output):
print(System.err, "*******\n");
print(System.err,"|");
print(System.out,"text");
print(System.err,"|");
print(System.err,"*******\n");
private void print(PrintStream ps, String output) {
ps.print(output);
ps.flush();
}
The fact is that System.out.print
buffers data for output, unlike System.err.print
.
What does this mean ?
For example, you type using System.out.println
. Then perform some operations, then print again. System.out.println
prints all the elements at once, not one at a time.
System.err.print
instantly prints items without buffering the data.
We solved the problem like this:
public static void main(String[] args) {
try {
System.err.print("**********\n| ");
System.err.flush();
Thread.sleep(50);
System.out.print("text");
System.out.flush();
Thread.sleep(50);
System.err.print(" |\n**********");
} catch (InterruptedException e) {
e.printStackTrace();
}
}