我知道這篇文章很古老,但今天仍然是一個問題,所以在這裏另一個解決方案使用@EserAygün的答案修復了這個問題,但以一種不需要你找到和修改項目中每個地方的方式您正在致信System.out
或System.err
。
自己創建一個名爲EclipseTools
,內容如下(和所需的包聲明和進口)類:
public class EclipseTools {
private static OutputStream lastStream = null;
private static boolean isFixed = false;
private static class FixedStream extends OutputStream {
private final OutputStream target;
public FixedStream(OutputStream originalStream) {
target = originalStream;
}
@Override
public void write(int b) throws IOException {
if (lastStream!=this) swap();
target.write(b);
}
@Override
public void write(byte[] b) throws IOException {
if (lastStream!=this) swap();
target.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
if (lastStream!=this) swap();
target.write(b, off, len);
}
private void swap() throws IOException {
if (lastStream!=null) {
lastStream.flush();
try { Thread.sleep(200); } catch (InterruptedException e) {}
}
lastStream = this;
}
@Override public void close() throws IOException { target.close(); }
@Override public void flush() throws IOException { target.flush(); }
}
/**
* Inserts a 200ms delay into the System.err or System.out OutputStreams
* every time the output switches from one to the other. This prevents
* the Eclipse console from showing the output of the two streams out of
* order. This function only needs to be called once.
*/
public static void fixConsole() {
if (isFixed) return;
isFixed = true;
System.setErr(new PrintStream(new FixedStream(System.err)));
System.setOut(new PrintStream(new FixedStream(System.out)));
}
}
然後,只需在你的代碼的開頭調用EclipseTools.fixConsole()
一次。問題解決了。
基本上,這將用兩個流System.err
和System.out
替換一組自定義的流,它們將數據簡單地轉發到原始流,但保持跟蹤哪個流被寫入最後。如果寫入的數據流發生更改(例如,System.err.something(...)
後跟System.out.something(...)
),則刷新最後一個數據流的輸出並等待200ms,以便Eclipse控制檯有時間完成打印。
注意:200ms只是一個粗略的初始值。如果此代碼減少但不能解決問題,請將Thread.sleep
中的延遲從200增加到某個更高的值,直到其工作。或者,如果這種延遲工作,但會影響代碼的性能(如果您經常交換流),您可以逐漸減少它,直到您開始出現錯誤。
你有沒有考慮過使用像Log4J這樣的專用日誌框架呢? – 2011-05-25 08:57:20
@Péter當然,這將是一種選擇,但我寧願如果有一個簡單的解決方案來解決這個問題(以備將來參考,如果沒有其他)。 – Ivan 2011-05-25 08:59:39