0
我想重定向我的輸出到一個文本區域(這是將要在一個JFrame的地方嵌入使用下面的代碼段標準輸出重定向與記錄儀
public static void main(String[] args) {
Logger.getLogger(MyClass.class.getName()).info("Test");
final JTextArea x = new JTextArea();
PrintStream printStream = new PrintStream(new OutputStream(){
@Override
public void write(int b) throws IOException {
x.append(String.valueOf((char)b));
x.setCaretPosition(x.getDocument().getLength());
}
});
System.setOut(printStream);
System.setErr(printStream);
Logger.getLogger(MyClass.class.getName()).info("Test again");
System.out.println("Another test");
JOptionPane.showMessageDialog(null, x.getText());
}
然而,最後一行執行時,該JOptionPane的文本只是「另一個測試」。 當我刪除第一記錄儀行
Logger.getLogger(MyClass.class.getName()).info("Test");
然後,一切都將被重定向到JTextArea中。我懷疑後,我在第一行登錄「測試」,該類記錄儀結合到控制檯輸出,並不會得到即使將stdout重定向到TextArea,也是如此。
可能發生的情況是getLogger保存與'System.out'關聯的'PrintStream',並保留對它的引用。因此你的結果。 – fge 2015-04-01 18:59:12