2013-05-08 49 views
0

像主題 - 我想如果一切都印入錯誤流做動作,但下面的代碼無法正常工作:做動作時的東西,印在System.err的

try { 
    System.setOut(new PrintStream("InfoLog.txt")); 
    System.setErr(new PrintStream(new FileOutputStream("ErrorLog.txt") { 
     public void write(int b) throws IOException { 
      super.write(b); 
      error(); 
     } 
     public void write(byte[] b) throws IOException { 
      super.write(b); 
      error(); 
     } 
    })); 
} catch (FileNotFoundException ex) { 
    Logger.getLogger(HouseCalc.class.getName()).log(Level.SEVERE, null, ex); 
} 

有什麼辦法「捕捉」System.err流並在打印到文件之前執行任何操作?

+0

你可以用'System.setErr()'設置'err'。因此,將其包裝在您自己的'PrintStream'中並覆蓋它,以便它執行某些操作。 – 2013-05-08 17:47:57

+0

我已經在上面的例子中這樣做了,但是這種方法不起作用。 – Mac70 2013-05-08 17:48:02

+1

什麼不適用於它?你可能不會壓倒正確的方法。 – 2013-05-08 17:48:47

回答

0

確保覆蓋合適的方法。仔細看看PrintStream的來源,因爲他們可能會打電話給彼此。你想一路下來。

write(char cbuf[], int off, int len) 

可能是你真正需要的。